无法设置自定义对象

时间:2015-05-24 11:01:50

标签: ios objective-c

我有一个自定义数据对象,我用它来存储从JSON请求传递的信息,但是当我尝试设置值时,一切都仍为空。

我仍然是iOS开发的新手,并且拥有更多的Java背景,所以我确信我只是错过了某些东西或做错了事。

我的班级:

BuildingLocation.h

#import <Foundation/Foundation.h>

@interface BuildingLocation : NSObject {
    NSString *_name;
    NSString *_description;
    NSString *_URL;
    float  _Long;
    float  _Lat;
    NSString *_Town;
    NSString *_Type;
    NSString *_Premium;
}

@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *description;
@property (nonatomic, copy) NSString *URL;
@property (nonatomic) float Long;
@property (nonatomic) float Lat;
@property (nonatomic, copy) NSString *Town;
@property (nonatomic, copy) NSString *Type;
@property (nonatomic, copy) NSString *Premium;

- (id)init:(NSString *)name description:(NSString *)description URL:(NSString *)URL Long:(float)Long Lat:(float)Lat Town:(NSString *)Town Type:(NSString *)Type Premium:(NSString *)Premium;

@end

BuildingLocation.m

#import "BuildingLocation.h"

@implementation BuildingLocation

@synthesize name = _name;
@synthesize description = _description;
@synthesize URL = _URL;
@synthesize Long = _Long;
@synthesize Lat =_Lat;
@synthesize Town = _Town;
@synthesize Type = _Type;
@synthesize Premium = _Premium;

-(id)init:(NSString *)name description:(NSString *)description URL:(NSString *)URL Long:(float)Long Lat:(float)Lat Town:(NSString *)Town Type:(NSString *)Type Premium:(NSString *)Premium {
    if ((self = [super init])) {
        self.name = name;
        self.description = description;
        self.URL = URL;
        self.Long = Long;
        self.Lat = Lat;
        self.Town = Town;
        self.Type = Type;
        self.Premium = Premium;
    }
    return self;
}

@end

我如何尝试在代码中设置值:

BuildingLocation *locationObject;
                locationObject.name = [location objectForKey:@"Name"];
                locationObject.description = [location objectForKey:@"Decription"];
                locationObject.URL = [location objectForKey:@"URL"];
                locationObject.Long = [[location objectForKey:@"Longitude"] floatValue];
                locationObject.Lat = [[location objectForKey:@"Lat"] floatValue];
                locationObject.Town = [location objectForKey:@"Town"];
                locationObject.Type = [location objectForKey:@"Type"];
                locationObject.Premium = [location objectForKey:@"Premium"];

                NSLog(@"Name before: %@", locationObject.name);

NSLog将locationObject.name的值赋予(null)

1 个答案:

答案 0 :(得分:1)

永远不会分配和初始化locationObject对象。

试试这个:

BuildingLocation *locationObject = [[BuildingLocation alloc] init]; // allocate and initialize this object.
//  ...
NSLog(@"Name before: %@", locationObject.name);