代码之家  ›  专栏  ›  技术社区  ›  Ryan Bavetta

子类NSCache-App Singleton

  •  0
  • Ryan Bavetta  · 技术社区  · 15 年前

    我正在写一个iPhone应用程序,我想创建一个NSCache单例。

    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 { 
        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)];
    

    问题:编译器抱怨 每一行。

    我可能做错了什么-知道怎么做吗?

    2 回复  |  直到 15 年前
        1
  •  1
  •   tc.    15 年前

    如果第一个清单是MyAppCache.h,那么您将@implementation放在头文件中,这不太可能是正确的(链接器可能会抱怨)。

    如果第一个列表是MyAppCache.m,那么需要将@interface移到MyAppCache.h中。

    [[MyAppCache alloc] init] 是有效的 [[[MyAppCache sharedCache] retain] init]

        2
  •  -2
  •   Ryan Bavetta    15 年前

    好的,明白了。我有一个MyAppCache.h和MyAppCache.m文件的副本(以前的版本)仍然放在项目的一个文件夹中!

    推荐文章