在过去的几天里,我到处找,除了几根头发外,几乎没有什么可看的。
我正试图通过@properties将我的对象数据从一个类传递到另一个类,所有这些都能很好地处理我的NSString对象。但我无法访问我的NSDictionary(和/或NSMutableDictionary)数据。事实上,我已经尝试过将我的NSDictionary切换到NSMutableDictionary,在保留和复制之间切换,以及其他一些变体,但都无济于事。
以下是明细。我正在传递的NSDictionary对象是projectMessagesList。我希望这是足够简短的代码,但提供足够的信息:
DBSProject.h
@interface DBSProject : NSObject <NSCoding>
@property (nonatomic, retain) NSDictionary *projectMessagesList;
@end
DBSProject.m
@implementation DBSProject
@synthesize projectMessagesList=_projectMessagesList;
-(id)init {
self = [super init];
if (self) {
[self setProjectCode:@"CODE"];
NSMutableDictionary *projectMessagesList = [[NSMutableDictionary alloc] init];
DBSMessage *message = [[DBSMessage alloc] init];
[message setMessageDate:[NSDate date]];
[message setMessageText:[NSString stringWithFormat:@"This is a message"]];
[projectMessagesList setObject:message forKey:@"msg"];
NSLog(@"%@", [projectMessagesList objectForKey:@"msg"]);
}
}
return self;
}
对象类末尾的NSLog在控制台中正确地打印出"这是一条消息"。
现在让我们跳到我的另一个类,一个ViewController:
DBSDetailViewController.h
#import "DBSProject.h"
#import "DBSMessage.h"
@interface DBSDetailViewController : UIViewController
@property (strong, nonatomic) DBSProject *myProject;
@property (strong, nonatomic) IBOutlet UILabel *clientCode;
@end
DBSDetailViewController.m
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSString *clientProjectString = [NSString stringWithFormat:@"%@ %@", self.myProject.clientCode, self.myProject.projectCode];
self.title = self.myProject.projectCode;
self.projectCode.text = clientProjectString;
self.projectDescription.text = self.myProject.projectDescription;
self.projectBudget.text = self.myProject.projectBudget;
self.projectDueDate.text = self.myProject.projectDueDate;
DBSMessage *tmpMessage = [[DBSMessage alloc] init];
tmpMessage = [self.myProject.projectMessagesList objectForKey:@"msg"];
NSLog(@"%@", self.myProject.projectCode);
NSLog(@"%@", [tmpMessage messageText]);
}
这正确地打印出了我的projectCode,但projectMessagesList(我的NSDictionary)是一个(null)。
因此,我可以访问除NSDictionary之外的所有内容。有人对我的错误有什么建议吗?非常感谢!
更改代码,这是一个非常简单的错误
-(id)init {
self = [super init];
if (self) {
[self setProjectCode:@"CODE"];
//you are not assigning the object into ivar..you are creating a local object
//NSMutableDictionary *projectMessagesList = [[NSMutableDictionary alloc] init];
//into
projectMessagesList = [[NSMutableDictionary alloc] init];
DBSMessage *message = [[DBSMessage alloc] init];
[message setMessageDate:[NSDate date]];
[message setMessageText:[NSString stringWithFormat:@"This is a message"]];
[projectMessagesList setObject:message forKey:@"msg"];
NSLog(@"%@", [projectMessagesList objectForKey:@"msg"]);
}
}
return self;
}