views:

53

answers:

2

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 { 
    return 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?

A: 

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.)

tc.
so, they are split into .h and .m files, I combined them here because I thought it would operate the same either way - (?)I don't think I'm ever calling [[MyAppCache alloc] init] specifically.A good amount of the code, including the copyWithZone comes from here (bottom of page):http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html
Ryan Bavetta
I'm editing the code now to show the division into .h and .m files
Ryan Bavetta
A: 

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!

Ryan Bavetta