Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

iphone - Singleton shared data source in Objective-C

Hey folks - I'm writing a pretty simple iPhone application. The data comes from a plist file (NSDictionary basically), that I'm trying to load into a singleton class and use across my various view controllers to access the data.

Here's the implementation for my singleton (heavily modeled after this thread)

@implementation SearchData

@synthesize searchDict;
@synthesize searchArray;

- (id)init {
    if (self = [super init]) {
        NSString *path = [[NSBundle mainBundle] bundlePath];
        NSString *finalPath = [path stringByAppendingPathComponent:@"searches.plist"];
        searchDict = [NSDictionary dictionaryWithContentsOfFile:finalPath];
        searchArray = [searchDict allKeys];
    }

    return self;
}

- (void)dealloc {
    [searchDict release];
    [searchArray release];
    [super dealloc];
}

static SearchData *sharedSingleton = NULL;

+ (SearchData *)sharedSearchData {
    @synchronized(self) {
        if (sharedSingleton == NULL)
            sharedSingleton = [[self alloc] init];
    }   
    return(sharedSingleton);
}

@end

So whenever I try to access the searchDict or searchArray properties elsewhere in my application (like a TableView delegate) like so:

[[[SearchData sharedSearchData] searchArray] objectAtIndex:indexPath.row]

I get an exception stating *** -[NSCFSet objectAtIndex:]: unrecognized selector sent to instance 0x5551f0

I'm not really sure why the objectAtIndex message is being sent to an NSCFSet object, I feel like my singleton is implemented wrong or something. I also tried a more complex singleton implementation like the one recommended by apple in the aforementioned thread and had the same problem. Thanks for any insight you can provide.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In your -init method you are directly accessing your instance variables and you are not retaining them. They're getting deallocated and their memory is being used up by other objects later on in your application's lifetime.

Either retain your objects that you're creating there or use the non-convenience methods to generate them.

searchDict = [[NSDictionary alloc] initWithContentsOfFile:finalPath];
searchArray = [[searchDict allKeys] retain];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...