我在我的 iPhone 应用程序中创建了以下单例:
#import "AppManager.h"
static AppManager *sharedAppManager = nil;
@implementation AppManager
@synthesize currentType, listOfTypes;
#pragma mark Singleton Methods
+ (id)sharedManager {
@synchronized(self) {
if (sharedAppManager == nil)
sharedAppManager = [[self alloc] init];
}
return sharedAppManager;
}
- (id)init {
if (self = [super init]) {
currentType = @"";
listOfTypes = [NSArray arrayWithObjects:@"T1", @"T2", @"T3", nil];
}
return self;
}
- (void)dealloc {
// Should never be called, but just here for clarity really.
[currentType release];
[listOfTypes release];
[super dealloc];
}
@end
当我使用它时:
// TEST
AppManager *appManager = [AppManager sharedManager];
NSArray *array = appManager.listOfTypes;
NSLog(@"TYPES:%@", array);
我有一个奇怪的事情...
TYPES:<UIButtonContent: 0x7b8db10 Title = (null), Image = <UIImage: 0x7bad7f0>, Background = (null), TitleColor = UIDeviceWhiteColorSpace 1 1, ShadowColor = UIDeviceWhiteColorSpace 0 0.5>
它在 currentType(NSString 属性)上工作正常,但在 listOfTypes(NSArray)上却不行
最佳答案
您没有保留数组 listOfTypes,因此该数组可能已被释放并指向一些垃圾值。使用以下内容保留数组(如果它是保留/复制的属性)。
self.listOfTypes = [NSArray arrayWithObjects:@"T1", @"T2", @"T3", nil];
您也可以简单地向阵列发送保留消息。
listOfTypes = [[NSArray arrayWithObjects:@"T1", @"T2", @"T3", nil] retain];
或者分配数组。
listOfTypes = [[NSArray alloc] initWithObjects:@"T1", @"T2", @"T3", nil];
关于iphone 应用程序 : cannot retrieve property from a Custom Singleton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7938717/