我正在编写一个iPhone应用程序,我想创建一个NSCache单例程序。
我遇到了麻烦,下面是我的代码:
MyAppCache.h:
#import <Foundation/Foundation.h>
@interface MyAppCache : NSCache {}
+ (MyAppCache *) sharedCache;
@endMyAppCache.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 {
return self;
}
- (NSUInteger)retainCount {
return NSUIntegerMax; //denotes an object that cannot be released
}
- (void)release{
//do nothing
}
- (id)autorelease {
return self;
}
@end当我想要添加一些东西或者从缓存中得到一些东西时,我可能会写:
#import "MyAppCache.h"
MyAppCache *theCache = [MyAppCache sharedCache]; 然后:
NSData *someData = [[theCache objectForKey: keyString] retain];或者:
[theCache setObject: someData forKey: keyString cost: sizeof(someData)];问题是:编译器抱怨'MyAppCache‘可能不会对每一行的“方法”做出响应。
我可能做错了什么-知道怎么做吗?
发布于 2010-08-18 04:42:13
好的,明白了。我有一个MyAppCache.h和MyAppCache.m文件的副本(以前的版本),它们仍然位于项目中的一个文件夹中!
发布于 2010-08-18 00:43:12
如果第一个清单是MyAppCache.h,那么将@implementation插入到头文件中,这不太可能做正确的事情(链接器可能会抱怨)。
如果第一个清单是MyAppCache.m,则需要将@接口移动到MyAppCache.h。
还请注意,您的代码受到双重输入的影响:[[MyAppCache alloc] init]实际上是[[[MyAppCache sharedCache] retain] init]。我不知道当输入两次时NSCache会做什么,但可能不是很好。我真的不想实现copyWithZone:(我很确定对象在默认情况下是不可复制的),而且您只需重写allocWithZone:来引发异常。
(并且+sharedCache不是线程安全的,这可能是一个问题,也可能不是一个问题。)
https://stackoverflow.com/questions/3507900
复制相似问题