這裏是可可的新手。我試圖在NSView中編碼一個實例變量以保存到文件中。但是,無論何時編碼它,它都會在調用initWithFrame時被覆蓋爲(null)。有沒有辦法可以跳過這種行爲並將實例變量加載到未歸檔的NSView?這裏是我的代碼有:如何保存一個NSView而不用它的實例變量被initWithFrame覆蓋:?
#import "Tragic.h"
@implementation Tragic {
NSColor *color;
}
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
NSLog(@"%@",color);
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect {
if(!color) {
color = [NSColor greenColor];
}
[color set];
color = [NSColor yellowColor];
NSRectFill([self bounds]);
}
-(void)encodeWithCoder:(NSCoder *)aCoder {
[super encodeWithCoder:aCoder];
[aCoder encodeObject:color forKey:@"color"];
}
-(id)initWithCoder:(NSCoder *)aDecoder {
if(self = [super initWithCoder:aDecoder]) {
color = [aDecoder decodeObjectForKey:@"color"];
}
return self;
}
@end
在上面的代碼中,我第一次設置顏色來填充爲綠色,剛剛的drawRect後:方法完成其更改爲黃色,這樣會保存顏色爲黃色。但是,儘管如此,它在initWithFrame:log註釋中恢復爲null,並且我再次獲得綠色屏幕。從外觀上看,唯一的辦法似乎是將數據從視圖中分離出來。但如果有一種更簡單的方法,任何人都可以幫助我嗎?
它如何被保存?你什麼時候編碼它?然後,如果對它進行編碼,則需要使用initWithCoder:方法重新創建,而不是initWithFrame:上面的代碼雖然很麻煩,但如果使用得當,應該可以正常工作。 – Wain
我正在使用基於文檔的應用程序。這是在保存文檔時編碼的。在使用NSKeyedArchiver存檔的主文件上有一個出口。 –
因此,構建應用程序的正確方法是在文檔中使用顏色屬性,並將其與文檔的其他內容一起保存,然後將其傳遞給視圖。文件管理員應該通過。這是MVC結構的基礎 - 模型存儲數據,視圖顯示它,控制器介於2. – Wain