I am new to iOS and passing parameters by value or reference ( I am from a Java/.NEt background ) is confusing to me. you see I have a sort of utility / Helper method that I pass to it an NSMutableDictionary, and then a file location, and ask for it yo unrchive data form the file to the dictionary I sent it. this is the helper method :
- (void)loadData:(NSMutableDictionary *)dictionary fromFile:(NSString *)fname {
dictionary = [ NSKeyedUnarchiver unarchiveObjectWithFile : [ self getFilePath:fname ] ] ;
if ( [dictionary.allKeys count] < 1 ) {
NSLog(@"Couldn't load file %@ ", fname);
} else {
NSLog(@"Loaded data from file %@ successfully", fname );
}
}
now I call this method in the following line of code
[ loadData: dataDict fromFile:@"data.archive"];
Now the problem is that by the end of the helper method , I have a variable called dictionary that does have values, but its not the original dictionary I passed from my calling line. What Am I Doing wrong?
As explained here - Passing arguments by value or by reference in objective C - in objective c parameters are passed by value and so a modification made to the parameter is modifying a value and not the actual value of the reference being passed in.
If you want to modify your dictionary you should prefix it with an ** to pass the value of the reference and then access with *.
- (void)loadData:(NSMutableDictionary**)dictionary fromFile:(NSString*)fname {
{
*dictionary = [NSKeyedUnarchiver unarchiveObjectWithFile:[self getFilePath:fname]];
if ([*dictionary.allKeys count] < 1) {
NSLog(@"Couldn't load file %@ ", fname);
}
else {
NSLog(@"Loaded data from file %@ successfully", fname);
}
}
Note: This sort of pointer dereferencing is a little funky and should probably restricted to **Error passing. It would probably make more sense to create a new dictionary copy content and return it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With