我正在尝试编写一个包含两个场景的应用。第一页是一个UITableView,它将包含一个音符条目列表。第二个场景有2个文本字段(注释摘要和注释说明)。我在第二个场景输入详细信息,然后单击“保存”按钮保存数据:
NoteListViewController.m
- (IBAction)saveAndGoBack:(id)sender {
NSLog(@"NoteDetailViewController.m: %@", NSStringFromSelector(_cmd));
NSString * desc = [[NSString alloc]init];
NSString * detail = [[NSString alloc]init];
desc = _noteTitle.text;
detail = _noteDesc.text;
[[NoteStore sharedStore]createNoteWithDesc:desc AndDetail:detail];
[self.navigationController popViewControllerAnimated:YES];
}
NoteStore是一个静态的sharedStore,我将数据保存到。
NoteStore.m
-(Notes *)createNoteWithDesc:(NSString *)desc AndDetail:(NSString *)detail {
NSLog(@"NoteStore.m: %@", NSStringFromSelector(_cmd));
Notes * newNote = [[Notes alloc]initNoteWithDesc:desc AndDetail:detail];
[self.privateItems addObject:newNote];
return newNote;
}
因此,该注释被添加到名为“privateItems”的NSMutableArray中。 我确认Note对象已正确添加。
*****当我尝试使用一个名为allItems的NoteStore.h文件中具有公共属性的访问器方法从privateItems数组中检索Note对象(desc和detail)时出现问题(它是一个NSArray只读,非原子和副本):
NoteStore.m
-(NSArray *)allItems{
NSLog(@"NoteStore.m: %@", NSStringFromSelector(_cmd));
return [self.privateItems copy];
}
每当我尝试检索它时,第一个属性(desc)出现为nil,而第二个属性(detail)有我保存在第二个场景的第二个文本字段中的数据。为什么第一个字段不断出现为nil ???
为了清楚起见, Note 对象声明如下
@interface Notes : NSObject
// What are the properties of a note?
@property (nonatomic, weak) NSString * noteDesc;
@property (nonatomic, weak) NSString * noteDetail;
@property (nonatomic, weak) NSString * test;
// Designated Initializer
-(instancetype)initNoteWithDesc:(NSString *)desc AndDetail:(NSString *)detail;
@end
非常感谢任何帮助。
答案 0 :(得分:1)
当您调用指定的初始化程序时,您传入了两个 NSString 对象。此时,它们由创建它们的方法所有。
当他们被分配到属性时,他们只有弱引用,因此保留计数不会被提升。弱引用适用于委托对象之类的东西。在这种情况下,您希望您的对象保持不变,因此通过将它们声明为 strong ,您说我希望这些属性在内存中保留并获取它们的所有权。