开发者

Get an integer from a plist for Objective-C iPhone dev

开发者 https://www.devze.com 2023-01-22 04:00 出处:网络
I have the following DataAll.plist: <array> <dict> <key>ID</key> <integer>1</integer>

I have the following DataAll.plist:

<array>
    <dict>
        <key>ID</key>
        <integer>1</integer>
        <key>Name</key>
        <string>Inigo Montoya</string>
    </dict>
  ....
</array>

I want to get the ID value from it. My code gets the Name correctly, but the ID is a weird value. Here's what I'm doing:

NSBundle *bundle = [NSBundle mainBundle];
NSString *plistPath = [bundle pathForResource:@"DataAll" ofType:@"plist"];

NSArray *array = [[NSArray alloc] initWithContentsOfFile:plistPath];
self.allData = array;
[array release];

NSDictionary *first = [[NSDictionary alloc]
        initWithDictionary:[self.allData objectAtIndex:0]];

Data *firstData = [[Data alloc] init];

[firstData setData:first];

labelName.text = [firstData EXName];
labelID.text = [NSString stringWithFormat:@"%d",[[firstData EXID]];
[firstData release];

Here's my Data.h

@interface Data : 开发者_如何学运维NSObject {
    NSNumber    *EXID;
    NSString    *EXName;
}
@property (readwrite, retain) NSNumber *EXID;
@property (nonatomic, retain) NSString *EXName;

And Data.m

@implementation Data
@synthesize EXID;
@synthesize EXName;

- (void) setData: (NSDictionary *) dictionary {
   self.EXName = [dictionary objectForKey:@"Name"];
   NSNumber *ID = [dictionary objectForKey:@"ID"];
   self.EXID = ID;
}

Many thanks in advance! This is my first post, so I apologize if formatting isn't correct.


The problem is in

[NSString stringWithFormat:@"%d",[[firstData EXID]];

EXID is an NSNumber* object and not an int so %d isn't what you want. You need to either replace %d with %@ or unwrap the integer from the NSNumber by calling [EXID integerValue] or [EXID intValue]. Which return NSInteger and int respectively.


Just because your data is in the plist as an integer doesn't mean it is retrieved as one. At least not when you retrieve with [dict objectForKey:]. Furthermore, NSNumber and integer are not the same data type.

My guess is the latter is throwing you off. That is to say the implicit conversion to NSNumber. Add the following before you call setData and update your OP with the output.

NSLog(@"plist entry: %@", first);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号