Unable to create mutable copy of NSDictionary - objective-c

UPDATE: Now working (added fixes as suggested - Thanks!)
I've been trying to clone an NSDictionary of employee info. The main NSDictionary is created in a different class and passed along in prepareForSegue. I want to be able to create a mutable copy of that NSDictionary in another class which can then update the employee info and send it off to another class for processing so I still have the original unchanged dataset to work with at a later time. I've found a few different examples on Stack, but nothing I could get working. When I break on the btn_click method and examine the local pp object after the ..objectForKey call, pp is still nil. What have I done wrong here?
obj_person.h
#import <Foundation/Foundation.h>
#interface obj_person : NSObject
#property (strong,nonatomic) NSString *personID;
#property (strong, nonatomic) NSString *personName;
#property (strong, nonatomic) NSString *personTitle;
#end
obj_person.m
#import "obj_person.h"
#implementation obj_person
#synthesize personID = _personID;
#synthesize personName = _personName;
#synthesize personTitle = _personTitle;
#end
viewcontroller.m
#import "ViewController.h"
#import "obj_person.h"
#interface ViewController ()
#end
#implementation ViewController
int mCounter = 1;
NSMutableDictionary *mCopy;
NSMutableDictionary *mNsd;
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *arnames = [[NSArray alloc] initWithObjects:#"mary", #"jane", #"stan", #"cartman", nil];
NSArray *arkeys = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2],[NSNumber numberWithInt:3], [NSNumber numberWithInt:4], nil];
mNsd = [[NSMutableDictionary alloc] initWithCapacity:[arnames count]];
int i = 0;
for (NSString *name in arnames)
{
obj_person *p = [[obj_person alloc] init];
p.personID = [arkeys objectAtIndex:i];
p.personName = name;
[mNsd setObject:p forKey:p.personID];
i++;
}
mCopy = [mNsd mutableCopy];
}
- (IBAction)btn_click:(id)sender
{
NSLog (#"%d original items", [mNsd count]);
obj_person *pp = [mCopy objectForKey:[NSNumber numberWithInt:mCounter]];
NSLog(#"%#", pp.personName);
pp.personName = #"Gerald";
if (++mCounter > [mCopy count])
mCounter = 1;
}
#end

Don't define:
NSMutableDictionary *mCopy;
NSMutableDictionary *mNsd;
Outside of the #interface and #implementation. They should be instance variables, so define instance variables or use properties to define them.
It's a good job you don't use n from:
for (NSArray *n in arnames)
because it isn't an NSArray, it's an NSString. You should fix that and you should probably both name it better than n and use it.
This:
obj_person *pp = [mCopy objectForKey:[NSNumber numberWithInt:1]];
fails because the key you originally stored with is an NSString instance and the thing you are using to try to get the data out is an NSNumber instance (so they can never match).

You might try:
mCopy = [mNsd mutableCopy];
[mCopy retain]
One theory is that the mutableCopy returns is an autoreleased object and it's being killed off before the btn_click function fires. According to this post: Retain/release of returned objects, mutableCopy should not be autoreleasing the array, but bugs do happen.
Else, maybe try iterating through with a for-loop instead.
int cnt = [arnames count];
for(int i=0; i<cnt; i++)
...

Related

Objective-C: How to create object instance with constructor that references arrays

I'm trying to create an array of objects, but it's not working as expected. I have a Person class with a name property and I'm trying to instantiate Person objects with the names from another array like the code below. Instead of the names in the names array being used, the program outputs "(null)". So that means that it's not working as expected.
ViewController.m
names = [NSArray arrayWithObjects:#"Mike", #"John", #"Jimmy", #"Tim", nil];
personsArray = [[NSMutableArray alloc] initWithCapacity:4];
for (int i = 0; i <= 4; i++) {
Person *person = [[Person alloc] initWithName:[names objectAtIndex:i]];
NSLog(#"%#", [person name]); // outputs "(null)"
[personsArray addObject:person];
}
Person.m
#import "Person.h"
#implementation Person
-(id)initWithName:(NSString *)name {
if (self = [super init]) {
name = name;
}
return self;
}
#end
Person.h
#import <Foundation/Foundation.h>
#interface Person : NSObject
#property (nonatomic, strong) NSString *name;
-(id)initWithName:(NSString *)name;
#end
Please help!
This line in -[Person initWithName:] is your problem:
name = name;
You are just assigning the argument variable to itself. You need to assign the instance variable. You probably want to copy the input string, so:
_name = [name copy];

Objective-C addObject seems to put object into all array indices

I am trying to learn how to make simple classes.
So far I am not getting the results expected using addObject and my class.
Here is what I have:
In my view controller:
#import "onoffclass.h"
In its viewDidLoad:
NSMutableArray *inTable;
onoffclass *therec;
onoffclass *readrec;
inTable = [NSMutableArray array];
therec = [[onoffclass alloc]init];
readrec = [[onoffclass alloc]init];
for (int lop=0;lop<3;lop++){
therec.parsedID = [NSString stringWithFormat:#"%i",lop];
[inTable addObject:therec];
NSLog(#"lop=%i onoff.parsedID=%#",lop,therec.parsedID);
for (int z=0;z<[inTable count];z++){
readrec = inTable[z];
NSLog(#" inTable[%i] parsedID=%#",z,readrec.parsedID);
}
}
In my onoffclass.h:
#interface onoffclass : NSObject
#property NSString *parsedID;
#property NSString *parsedOn;
#property NSString *parsedOff;
#property NSString *parsedAdj;
#property NSString *parsedRoom;
#property NSString *parsedBuilding;
#property NSString *parsedWho;
#property NSString *parsedInfo;
#property NSString *parsedBillable;
-(onoffclass*)initWithSomeString: (NSString*)blah AndSomeNum: (int)num;
-(NSString*)description;
#end
In my onoffclass.m:
#import <Foundation/Foundation.h>
#import "onoffclass.h"
#implementation onoffclass {
NSString *_parsedID;
NSString *_parsedOn;
NSString *_parsedOff;
NSString *_parsedAdj;
NSString *_parsedRoom;
NSString *_parsedBuilding;
NSString *_parsedWho;
NSString *_parsedInfo;
NSString *_parsedBillable;
}
-(onoffclass*)initWithSomeString: (NSString*)blah AndSomeNum: (int)num {
self = [super init];
_parsedID = blah;
_parsedOn = #"on";
_parsedOff = #"off";
_parsedAdj = #"adj";
_parsedRoom = #"room";
_parsedBuilding = #"building";
_parsedWho = #"who";
_parsedInfo = #"info";
_parsedBillable = #"billable";
return self;
}
-(NSString*)description {
return [NSString stringWithFormat: #"%#", _parsedID];
}
#end
Here is the output:
lop=0 onoff.parsedID=0
inTable[0] parsedID=0
lop=1 onoff.parsedID=1
inTable[0] parsedID=1
inTable[1] parsedID=1
lop=2 onoff.parsedID=2
inTable[0] parsedID=2
inTable[1] parsedID=2
inTable[2] parsedID=2
Why does it appears that addObject is updating all array indices and how do I fix this?
Thanks,
Dale
You are creating one instance of onoffclass (by the way class names should start with a capital letter) then you are adding the same instance again and again in the loop. Since classes are reference types changing a property affects all occurrences of the same instance.
Solution is to put the line to create an instance in the loop
for (int lop = 0; lop < 3; lop++) {
therec = [[onoffclass alloc] init];
...

this method crashes if I use a property and works fine if I declare the variable within the method--why?

I'm working on a programmable calculator, and for the life of me I can't understand what I'm doing wrong.
Here are the relevant parts of the code. (The code is unfinished, so I know there's extra stuff floating around.)
CalculatorViewController.m
#import "CalculatorViewController.h"
#import "CalculatorBrain.h"
#interface CalculatorViewController ()
#property (nonatomic) BOOL userIsEnteringNumber;
#property (nonatomic) BOOL numberIsNegative;
#property (nonatomic,strong) CalculatorBrain *brain;
#property (nonatomic) NSArray *arrayOfDictionaries;
#property (nonatomic) NSDictionary *dictionary;
#end
#implementation CalculatorViewController
#synthesize display = _display;
#synthesize history = _history;
#synthesize userIsEnteringNumber = _userIsEnteringNumber;
#synthesize numberIsNegative;
#synthesize brain = _brain;
#synthesize arrayOfDictionaries;
#synthesize dictionary;
-(CalculatorBrain *)brain
{
if (!_brain) _brain = [[CalculatorBrain alloc] init];
return _brain;
}
/*snip code for some other methods*/
- (IBAction)variablePressed:(UIButton *)sender
{
NSString *var = sender.currentTitle;
NSDictionary *dict = [self.dictionary initWithObjectsAndKeys:[NSNumber numberWithDouble:3],#"x",[NSNumber numberWithDouble:4.1],#"y",[NSNumber numberWithDouble:-6],#"z",[NSNumber numberWithDouble:8.7263],#"foo",nil];
[self.brain convertVariable:var usingDictionary:dict];
self.display.text = [NSString stringWithFormat:#"%#",var];
self.history.text = [self.history.text stringByAppendingString:sender.currentTitle];
[self.brain pushOperand:[dict objectForKey:var] withDictionary:dict];
}
#end
And here's CalculatorBrain.m.
#import "CalculatorBrain.h"
#interface CalculatorBrain ()
#property (nonatomic, strong) NSMutableArray *operandStack;
#end
#implementation CalculatorBrain
#synthesize operandStack = _operandStack;
-(void)pushOperand:(id)operand withDictionary:(NSDictionary *)dictionary
{
NSNumber *operandAsObject;
if (![operand isKindOfClass:[NSString class]])
{
operandAsObject = operand;
}
else
{
operandAsObject = [dictionary objectForKey:operand];
}
[self.operandStack addObject:operandAsObject];
}
-(double)popOperand
{
NSNumber *operandAsObject = [self.operandStack lastObject];
if (operandAsObject) [self.operandStack removeLastObject];
return [operandAsObject doubleValue];
}
-(double)convertVariable:(NSString *)variable usingDictionary:dictionary
{
double convertedNumber = [[dictionary objectForKey:variable] doubleValue];
return convertedNumber;
}
#end
The thing I'm having trouble understanding is in the CalculatorViewController.m method - (IBAction)variablePressed:(UIButton *)sender. This line crashes the program:
NSDictionary *dict = [self.dictionary initWithObjectsAndKeys:[list of objects and keys]];
But if I make it
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:[list of objects and keys]];
then everything works fine. But if I try to do
NSDictionary *dict = [[self.dictionary alloc] initWithObjectsAndKeys:[list of objects and keys]];
which seems to me the right thing to do, then XCode won't let me, so I'm obviously not understanding something.
Any thoughts?
+alloc allocates memory for an object. -init... methods initialize the object.
[self.dictionary initWithObjectsAndKeys:... calls -dictionary which is either going to return a dictionary set in that property or nil and then attempts to call init... on it. If the dictionary exists then you are attempting to initialize an object more than once which is not valid. If the property has not been set then the getter will return nil and sending an init... message to nil will do nothing. Either way this is not what you want to do.
[[self.dictionary alloc] init... is also invalid, as the compiler warns you. Now you try to obtain an object from -dictionary and then call the class method +alloc on it.
There seems to be some fundamental confusion here about how objects are created and what property accessors do. I'm not sure how to address that besides suggesting looking at object creation and dot syntax.

How to add objects from an NSArray to the end of an NSMutableArray?

So I need to add the objects from an NSArray that the user has chosen using an NSOpenPanel and put all the filenames into this array. Then I have an NSMutableArray called arguments that I am putting the arguments programmatically. Then I need to add these objects from the NSArray to the end of this NSMutableArray. So I use [NSMutableArray addObjectsFromArray:NSArray] and that keeps giving me an error.
This is what I'm doing with the code:
AppDelegate.h
#import <Cocoa/Cocoa.h>
#interface ZipLockAppDelegate : NSObject <NSApplicationDelegate> {
IBOutlet NSTextField *input;
IBOutlet NSTextField *output;
IBOutlet NSTextField *password;
NSArray *filenames;
NSMutableArray *arguments;
NSArray *argumentsFinal;
}
#property (assign) IBOutlet NSWindow *window;
#property (retain) NSArray *filenames;
#property (copy) NSMutableArray *arguments;
- (IBAction)chooseInput:(id)sender;
- (IBAction)chooseOutput:(id)sender;
- (IBAction)createZip:(id)sender;
#end
AppDelegate.m
#import "ZipLockAppDelegate.h"
#implementation ZipLockAppDelegate
#synthesize window = _window;
#synthesize filenames;
#synthesize arguments;
- (IBAction)chooseInput:(id)sender {
NSOpenPanel *openZip = [[NSOpenPanel alloc] init];
[openZip setCanChooseFiles:YES];
[openZip setCanChooseDirectories:YES];
[openZip setCanCreateDirectories:NO];
[openZip setAllowsMultipleSelection:YES];
[openZip setTitle:#"Select All Files/Folders to be zipped"];
int result = [openZip runModal];
if (result == 1) {
filenames = [openZip filenames];
}
}
- (IBAction)createZip:(id)sender {
[progress startAnimation:self];
arguments = [NSMutableArray arrayWithObjects:#"-P", [password stringValue], [output stringValue], nil];
[self.arguments addObjectsFromArray:filenames];
argumentsFinal = [[NSArray alloc] initWithArray:self.arguments];
NSTask *makeZip = [[NSTask alloc] init];
[makeZip setLaunchPath:#"/usr/bin/zip"];
[makeZip setArguments:argumentsFinal];
[makeZip launch];
[makeZip waitUntilExit];
[progress stopAnimation:self];
}
And this is the error I keep getting in the log. I can't figure out why I'm getting this.
EXC_BAD_ACCESS(code=13,address=0x0)
This points to the line [arguments addObjectsFromArray:filenames];
I can only make out the first part about the selector and the instance but I don't know what it means. Help...
Be consistent. To begin with, prefix all your instance variables with an underscore, not just some of them.
// Change this...
#synthesize window = _window;
#synthesize filenames;
#synthesize arguments;
//...to this
#synthesize window = _window;
#synthesize filenames = _filenames;
#synthesize arguments = _arguments;
Then you won't be able to do this anymore:
arguments = [NSMutableArray arrayWithObjects:#"-P", [password stringValue], [output stringValue], nil];
Note that on the very next line, you're doing this:
[self.arguments addObjectsFromArray:filenames];
Again, being consistent in using properties rather than directly accessing instance variables will help you avoid these kinds of errors. So rewrite the previous line to use the property, like so:
self.arguments = [NSMutableArray arrayWithObjects:#"-P", [password stringValue], [output stringValue], nil];
The compiler translates self.arguments = someArg into [self setArguments:someArg]. In this case the setter method is needed to retain the object so that it won't be deallocated while the reference is still stored in the _arguments instance variable.
Have you tried debugging it to see if filenames is ever initialized? Looking at your crashlog, you are referencing a nil pointer. It seems either filenames or arguments is never initialized.
Also, try and set your arguments array to a retain type rather than copy.
You also seem to keep going back and forth with your references. If you don't want to keep typing self.arguments, create an ivar in your synthesize statement and just stick with that.
#synthesize filenames = _filenames;
#synthesize arguments = _arguments;
[_arguments addObjectsFromArray:_filenames];
Your arguments object is an NSArray, not an NSMutableArray. You can only add objects to a mutable array, by definition. Try this:
arguments = [NSMutableArray arrayWithObjects:#"-P", [password stringValue], [output stringValue], nil];

#property retain OR copy

First I read this article
I think I should use "copy" in my programe.
Problem is using NSMutableDictionary copy it will terminate.
***** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary removeAllObjects]: mutating method sent to immutable object'**
I have no idea about "mutating method sent to immutable object".
I didn't set NSDictionary to NSMutabledictionary pointer.
Here is my code
.h file
#interface Button : NSObject {
#private
NSString* gID;
NSString* gBackColor;
NSString* gIconImage;
int gIndex;
BOOL gEnable;
BOOL gVisible;
NSString* gText;
NSMutableDictionary* gEvents;
BOOL gUseCircle;
}
#property (nonatomic,copy) NSString *ID;
#property (nonatomic,copy) NSString *BackColor;
#property (nonatomic,copy) NSString *IconImage;
#property int Index;
#property BOOL Enable;
#property BOOL Visible;
#property (nonatomic,copy) NSString *Text;
#property (nonatomic,getter=getEvents,retain) NSMutableDictionary *Events;
#property BOOL UseCircle;
#end
.m file
#implementation Button
#synthesize ID = gID;
#synthesize BackColor = gBackColor;
#synthesize IconImage = gIconImage;
#synthesize Index = gIndex;
#synthesize Enable = gEnable;
#synthesize Visible = gVisible;
#synthesize Text = gText;
#synthesize Events = gEvents;
#synthesize UseCircle = gUseCircle;
-(NSMutableDictionary*) getEvents
{
if (!gEvents)
{
gEvents = [[NSMutableDictionary alloc] initWithCapacity:20];
}
return gEvents;
}
- (id) init
{
self = [super init];
if (self != nil)
{
gID = #"";
gBackColor = #"";
gIconImage = #"";
gIndex = 0;
gText = #"";
gUseCircle = NO;
}
return self;
}
- (void) dealloc
{
[gID release];
[gBackColor release];
[gIconImage release];
[gText release];
[gEvents removeAllObjects];
[gEvents release];
gEvents = nil;
[super dealloc];
}
And implement
tBtnXML.Events = [self SplitEvents:tNode];
SplitEvents function:
-(NSMutableDictionary*) SplitEvents:(NSDictionary*)pEvents
{
NSMutableDictionary *tEvents = [[NSMutableDictionary alloc] initWithCapacity:5];
// code blabla
//.
//.
//.
[tEvents setObject:tEvent forKey:[NSNumber numberWithInt:tEventName]];
[tEvent release];
return [tEvents autorelease];
}
But I chage NSMutableDictionary* gEvents property from copy to retain , it execute normal.
Colud anyone tell me what's wrong with my code?
If my code is incorrect with dealloc,please tell me.
Thank you appriciate.
Yes, So I fixed my setter:
-(void) setEvents:(NSMutableDictionary*) pEvents
{
NSMutableDictionary* tNewDict = [pEvents mutableCopy];
[gEvents removeAllObjects];
[gEvents release];
gEvents = tNewDict;
}
This work with no error.
It helps me a lot.
But I can't vote up >"<~
So thank you Bavarious :)
In general, mutable properties should be retain instead of copy. When you declare a property as being copy, the synthesised setter method sends -copy to the object that’s being assigned to the property. In the case of mutable objects (e.g. NSMutableDictionary), sending -copy to them makes an immutable copy, effectively creating an object of immutable type (e.g. NSDictionary) instead.
So in:
tBtnXML.Events = [self SplitEvents:tNode];
the synthesised setter sends -copy to [self SplitEvents:tNode], thus creating an immutable copy of that dictionary (i.e., an NSDictionary instance), and assign it to gEvents. This is the cause of your error: gEvents is declared as NSMutableDictionary but points to an NSDictionary instead.
For the record, mutable classes usually declare a -mutableCopy method that does make a mutable copy. It is not used by declared properties, though. If you do not want to use retain, you need to implement a custom setter that uses -mutableCopy.