I have another question for you that I believe I already know WHY it isn’t working, but I’m not sure how to fix it…
I have a database array object using MutableNSArray. Let’s call it “Database”. This is an array of objects of type DatabaseRecord. I also have another DatabaseRecord object called CurrentRecord which is the active object I manipulate from the user interface. When I add a new entry into the database, I call:
[Database addObject: CurrentRecord];
When I’m done making changes, I replace the added record in the database with:
[Database replaceObjectAtIndex: <index> withObject: CurrentRecord];
What I just realizes was that CurrentRecord is a pointer defined as:
DatabaseRecord *CurrentRecord;
I believe that what is happening is that each and every new entry in the database sets itself to the values of CurrentRecord. Likewise, when I change CurrentRecord, all of objects in the NSArray modify themselves accordingly, so I’m left with a database of, say, 100 records that are all identical.
What I want to do is essentially COPY the values of CurrentRecord into the appropriate object in the MutableNSArray.
I’m sure there’s an easy fix to this, such as not passing a pointer, but I’m not quite sure how to proceed. I hope I’m being clear in my question…
If you’re changing records that are already in the array, there’s no need to replace anything. Do this:
Now you’ve just changed the contents of two of the records in the database — no need to replace anything. The reason you can do this is that
currentRecordis just a pointer to an object that already exists.If you want to modify every record in the array, you can do:
When you’re adding new records to the database, on the other hand, you’ll need to make sure that you create new objects each time. You can do that by copying an existing object, or by instantiating a new object each time yourself:
or:
If you’re not using ARC, you’ll need to release the objects you create appropriately, as shown in the comments above.
Nope. The only way to refer to an object in Objective-C is via pointer. The fix isn’t difficult, though — you just need to understand how pointers work a little better.