开发者

Subclass NSCache - App Singleton

I am writing an iPhone app and I want to create a NSCache singleton.

I am having trouble, here's the code that I have:

MyAppCache.h:

#import <Foundation/Foundation.h>

@interface MyAppCache : NSCache {}

+ (MyAppCache *) sharedCache;

@end

MyAppCache.m:

#import "SpotmoCache.h"

static MyAppCache *sharedMyAppCache = nil;

@implementation MyAppCache

+ (MyAppCache *) sharedCache {
    if (sharedMyAppCache == nil) {
        sharedMyAppCache = [[super allocWithZone:NULL] init];
    }
    return sharedMyAppCache; 
}

+ (id)allocWithZone:(NSZone *)zone {
    return [[self sharedCache] retain]; 
}

- (id)copyWithZone:(NSZone *)zone { 
    return self;
}

- (id)retain { 
    r开发者_如何学JAVAeturn self;
}

- (NSUInteger)retainCount {
    return NSUIntegerMax;  //denotes an object that cannot be released 
}

- (void)release{
    //do nothing
}

- (id)autorelease {
    return self; 
}

@end

When I want to add something or get something from the cache I might write:

#import "MyAppCache.h"

MyAppCache *theCache = [MyAppCache sharedCache];  

Then:

NSData *someData = [[theCache objectForKey: keyString] retain];

Or:

[theCache setObject: someData forKey: keyString cost: sizeof(someData)];

The problem: the compiler complains 'MyAppCache' may not respond to 'method' for each of those lines.

I might be doing something completely wrong here - know how to make this work?


If the first listing is MyAppCache.h, then you're sticking @implementation in a header file, which isn't likely to do the right thing (the linker will probably complain).

If the first listing is MyAppCache.m, then you need to move the @interface into MyAppCache.h.

Also note that your code suffers from double-initing: [[MyAppCache alloc] init] is effectively [[[MyAppCache sharedCache] retain] init]. I don't know what NSCache does when inited twice, but it probably isn't good. I really wouldn't bother implementing copyWithZone: (I'm pretty sure objects aren't copyable by default), and you can just override allocWithZone: to raise an exception.

(And +sharedCache isn't thread-safe, which may or may not be an issue.)


OK, got it. I had a copy (previous version) of the MyAppCache.h and MyAppCache.m files still sitting in a folder in the project!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜