Reputation: 24770
I have an algorithm that worked fine until I decided to make the local variable into a class object. The code is:
NSArray*parseLine=[newline componentsSeparatedByString:@","];
float percentx=[[parseLine objectAtIndex:1] floatValue];
//this NSLog prints fine and shows good values for all three items
NSLog(@"parsline:%@ and %@ and percentx: %f",[parseLine objectAtIndex:0], [parseLine objectAtIndex:1], percentx);
[self.data setObject:[NSNumber numberWithFloat:percentx] forKey:[parseLine objectAtIndex:0]];
//this NSLog shows (null) for the [self.data objectForKey:]
NSLog(@"%@ %f %@", [parseLine objectAtIndex:0] ,percentx, [self.data objectForKey:[parseLine objectAtIndex:0]]);
I'm baffled how [self.data objectForKey:key]
could be null when the setObject
statement for this NSMutableDictionary
object called "data" is using valid items. The NSNumber
is perhaps the issue, but all of this worked fine when "data" was just a locally alloc/init object.
In fact, "data" is not sent data at all. Later I can do this:
NSLog(@"%i",[data count]);
And it returns 0.
Upvotes: 0
Views: 616
Reputation: 397
ok, i see the problem, you don't quite have a solid understanding of how ivars and properties work. TRY THIS:
In your .h file...
@interface YourClassName
NSMutableDictionary *data;
@end
@property(nonatomic, retain) NSMutableDictionary *data;
In your .m file...
@implementation YourClassName
@synthesize data
- (id) initWithFrame:(CGRect) frame {
// Other init code here
self.data = [NSMutableDictionary dictionary];
}
Now you can reference self.data everywhere in your class.
don't forget [data release]; in the dealloc method.
Does that make sense?
Upvotes: 0
Reputation: 36143
You need to create a dictionary and assign it to self.data
prior to using self.data
, for example, during your class's designated initializer (assumed to be -init
for this example):
- (id)init
{
self = [super init];
if (!self) return self;
data = [[NSMutableDictionary alloc] init];
return self;
}
Almost all messages to nil
return 0/NO/false/NULL/nil/Nil. (Some messages have undefined effects when sent to a nil
object/Nil
class.) This is how you can get a 0 count and a nil
object for your key: you have a nil
dictionary.
Upvotes: 1
Reputation: 397
Is data marked as retain in your header? self.data is not necessarily equivalent to data by itself as self.data is a property for the ivar data.
Perhaps post how you are initializing self.data?
Upvotes: 1