我正在開發iphone應用程序。如何使用NSCoder
我使用NSCoder。
MyApplication.h
#define ITEMS_KEY @"items"
#define CATEGORIES_KEY @"categories"
#import <UIKit/UIKit.h>
@interface MyApplicationData : NSObject <NSCoding, NSCopying> {
NSMutableArray* items;
NSMutableArray* categories;
}
@property (nonatomic ,retain) NSMutableArray* items;
@property (nonatomic, retain) NSMutableArray* categories;
@end
Myapplication.m
#import "MyApplicationData.h"
@implementation MyApplicationData
@synthesize items;
@synthesize categories;
#pragma mark NSCoding
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:items forKey:ITEMS_KEY];
[aCoder encodeObject:categories forKey:CATEGORIES_KEY];
}
-(id)initWithCoder:(NSCoder *)aDecoder{
if(self = [super init]){
self.items = [aDecoder decodeObjectForKey:ITEMS_KEY];
self.categories = [aDecoder decodeObjectForKey:CATEGORIES_KEY];
}
return self;
}
#pragma mark -
#pragma mark NSCopying
-(id)copyWithZone:(NSZone *)zone{
MyApplicationData* copy = [[[self class]allocWithZone:zone]init];
items = [self.items copy];
categories = [self.categories copy];
return copy;
}
@end
但WARNNING。
'NSCoder' may not respond to '-decodeDataObjectForKey'
如何使用NSCoder?
任何需要提醒的是誰保留或複製這些對象也需要一個鏈接到內存管理規則:http://developer.apple.com/mac/library/documentation/General/Conceptual/DevPedia-CocoaCore/MemoryManagement.html – 2009-11-09 16:07:17
添加了正在編寫的源代碼。這是問題嗎? – marcy 2009-11-10 07:00:14
我在您發佈的代碼中看到的最大問題是您不保留從編碼器中檢索的值。 – 2009-11-12 16:20:47