我从我的 Xcode 4.5.2 编译器收到一条消息:
Property 'name' not found for object of type 'Checklist'
在 DataModel.m 的这行代码上:
Checklist.name = @"List";
问题是已经在 Checklist.h 中进行了属性声明,而 Checklist.h 已导入 DataModel.m。那么为什么会发生这个错误呢?
清单.m
#import <Foundation/Foundation.h>
@interface ChecklistItem : NSObject <NSCoding>
@property (nonatomic, copy) NSString *text;
@property (nonatomic, assign) BOOL checked;
- (void) toggleChecked;
@end
这是 DataModel.m 文件:
#import "DataModel.h"
#import "Checklist.h"
@implementation DataModel
- (NSString *)documentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return documentsDirectory;
}
- (NSString *)dataFilePath
{
return [[self documentsDirectory] stringByAppendingPathComponent:@"Checklists.plist"];
}
- (void)saveChecklists
{
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:self.lists forKey:@"Checklists"];
[archiver finishEncoding];
[data writeToFile:[self dataFilePath] atomically:YES];
}
- (void)loadChecklists
{
NSString *path = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:path])
{
NSData *data = [[NSData alloc] initWithContentsOfFile:path];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
self.lists = [unarchiver decodeObjectForKey:@"Checklists"];
[unarchiver finishDecoding];
}
else
{
self.lists = [[NSMutableArray alloc] initWithCapacity:20];
}
}
- (void)registerDefaults
{
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:-1], @"ChecklistIndex",
[NSNumber numberWithBool:YES], @"FirstTime",
nil];
[[NSUserDefaults standardUserDefaults]registerDefaults:dictionary];
}
- (void)handleFirstTime
{
BOOL firstTime = [[NSUserDefaults standardUserDefaults] boolForKey:@"FirstTime"];
if(firstTime) {
Checklist *checklist = [[Checklist alloc] init];
Checklist.name = @"List"; // error message appears here
[self.lists addObject:checklist];
[self setIndexOfSelectedChecklist:0];
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"FirstTime"];
}
}
- (id)init
{
if((self = [super init])) {
[self loadChecklists];
[self registerDefaults];
[self handleFirstTime];
}
return self;
}
- (int)indexOfSelectedChecklist
{
return [[NSUserDefaults standardUserDefaults]integerForKey:@"ChecklistIndex"];
}
- (void)setIndexOfSelectedChecklist
{
[[NSUserDefaults standardUserDefaults]setInteger:index forKey:@"ChecklistIndex"];
}
@end
Checklist.h(已更正)
#import <Foundation/Foundation.h>
@interface Checklist : NSObject<NSCoding>
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) NSMutableArray *items;
@end