【问题标题】:I'm having problems using a Singleton to pass an array in Objective-c. (code included)我在使用 Singleton 在 Objective-c 中传递数组时遇到问题。 (包括代码)
【发布时间】:2012-03-20 22:33:29
【问题描述】:

所以我正在创建一个名为 fruits 的数组,我想在多个视图之间共享它。这是我的代码:

#import <foundation/Foundation.h>
@interface MyManager : NSObject {
    NSMutableArray *fruits;
}
@property (nonatomic, retain) NSMutableArray *fruits;
+ (id)sharedManager;
@end

#import "MyManager.h"
static MyManager *sharedMyManager = nil;
@implementation MyManager
@synthesize fruits;
#pragma mark Singleton Methods
+ (id)sharedManager {
    @synchronized(self) {
        if (sharedMyManager == nil)
            sharedMyManager = [[self alloc] init];
    }
    return sharedMyManager;
}
- (id)init {
    if ((self = [super init])) {
        fruits = [[NSMutableArray alloc] init];
    }
    return self;
}
-(void) dealloc{
    self.fruits = nil;
    [super dealloc];
}
@end

现在我正在使用以下代码,以便在新视图中使用锻炼

#import "MyManager.h"
@interface Chest : UIViewController {
    IBOutlet MyManager *fruits;
}
@property (nonatomic, retain) IBOutlet MyManager *fruits;
-(IBAction) goToList: (id) sender;
@end

当一个按钮被点击时,goToList 被调用,我填充我的数组,fruits

#import "Chest.h"
@implementation Chest
@synthesize fruits;
-(IBAction) goToList:(id)sender{
    MyManager *fruits = [MyManager sharedManager];
    NSString *filePath;
    NSString *fileContents;
    filePath = [[NSBundle mainBundle] pathForResource:@"chest_strength" ofType:@"csv"];
        fileContents = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
        fruits = [fileContents componentsSeparatedByString:@"\n"];
}

当我在这个视图中输出 *fruits 的元素时,一切正常。现在,当我尝试在另一个视图中访问同一个变量时,它说数组为空。这是第二个视图的代码:

@interface List : UIViewController {
    IBOutlet MyManager *fruits;
}
@property (nonatomic, retain) IBOutlet MyManager *fruits;
@end

#import "List.h"
#import "MyManager.h"
@implementation List
@synthesize fruits
NSLog(@"%@", fruits);  //This is the part that isn't displaying correctly.  I'm getting a null here

所以我的问题是,我该怎么做才能获得我在 Chest 中填充的数组 fruits 并在 List 中使用它,以便我可以在该视图中显示数组的内容?

感谢所有回答的人。这个问题严重困扰着我,我需要尽快完成这个项目。非常感谢。

【问题讨论】:

  • 您的阵列是命名为workouts 还是fruits?您给出的代码示例内部不一致。
  • 在 chest.m 中,您将 NSArray* 分配给 fruits,它的类型是 MyManager*。您想将其分配给 fruits.fruits。
  • 你的静态变量 sharedMyManager 是全局的。这不完全是单例模式的意义所在。您应该将其声明为类变量;只需将其移至 implementationaiton 语句之后,使其成为 MyManager 的一部分,而不是全局的。抱歉,这不能回答您的问题。
  • @Hermann:这不是全球性的,而是static。将文件级变量声明为 static 会限制其对该文件的可见性。它不需要在@implementation 块内,将它放在那里不会改变它的可见性,也不会把它变成一个类变量,因为在 ObjC 中没有这样的东西。
  • 尤利乌斯,谢谢。每天都瘦点东西是件好事。下次有机会我会试试的。

标签: objective-c arrays view uiviewcontroller singleton


【解决方案1】:

您在这个问题中更改了一些内容,但基本问题仍然存在:数组是您的单例的属性,您没有将其视为这样。

每当您在单例之外引用数组时,都可以这样做:

[MyManager sharedManager].fruits

如果您经常访问它,您可以创建一个本地 ivar,但您肯定不会将它作为一个 IBOutlet,就像您在上一个代码示例中所做的那样。这将如何设置?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多