On touch up inside of SAVE button, the following code is executed:
- (IBAction)onSave:(id)sender {
savecount++;
[self saveNumberOfContacts];
NSMutableArray *myArray = [[NSMutableArray alloc] init];
[myArray addObject:nameTextField.text];
[myArray addObject:phoneTextField.text];
[myArray addObject:addressTextField.text];
[myArray addObject:cityTextField.text];
[myArray addObject:stateTextField.text];
[myArray addObject:zipcodeTextField.text];
[myArray writeToFile:[self saveFilePath] atomically:YES];
}
This creates a single array. I want to know how to dynamically create multiple arrays with the savecount variable suffixed at end of the array name.
For example, if my savecount is 3, then myArray1, myArray2, myArray3 should be created.
P.S. savecount changes its value dynamically.
EDIT: i dont want this method creating a number of arrays every time i call it. See, the user's info is stored in myArray1 when i click save for the first time. Now, the savecount gets increemented(say,savecount=2). When i enter another user's details and click save, i dont want myArray1 to be overwritten or disturbed; the second user's details must be independently saved in myArray2.
NSMutableArray *holder;
- (void)viewDidLoad
{
holder = [[NSMutableArray alloc] init];
}
- (IBAction)onSave:(id)sender {
savecount++;
[self saveNumberOfContacts];
NSMutableArray *myArray = [[NSMutableArray alloc] init];
[myArray addObject:nameTextField.text];
[myArray addObject:phoneTextField.text];
[myArray addObject:addressTextField.text];
[myArray addObject:cityTextField.text];
[myArray addObject:stateTextField.text];
[myArray addObject:zipcodeTextField.text];
[myArray writeToFile:[self saveFilePath] atomically:YES];
[holder addObject:myArray];
}
Have one global array in which you can hold dynamically created array. Now when you get value from holder, you will have separated myArray object.
If you are only using these arrays within one method, you could instead store the arrays in an array. This doesn't give you array names such as myArray1, myArray2, etc, but accomplishes the same overall task. Here's an example:
NSMutableArray *myArrays = [[NSMutableArray alloc] initWithCapacity:savecount];
for (NSUInteger i = 0; i < savecount; i++) {
NSMutableArray *newArray = [[NSMutableArray alloc] init];
[myArrays addObject:newArray];
[newArray addObject:nameTextField.text];
// continue adding your objects to newArray
}
Now you can reference your arrays as [myArrays objectAtIndex:0]...[myArrays objectAtIndex:savecount-1].
I think your problem is the path of save, or same path with appended array data.
If save data to different path:
- (NSString*)saveFilePath{
return [NSString stringWithFormat:#"%#/%#%d.%#", thePathToSave, fileName, savecount, fileType];
}
If save to same path with appended array data:
Replace:
[myArray writeToFile:[self saveFilePath] atomically:YES];
with
NSArray *fileData = [NSArray arrayWithContentsOfFile:[self saveFilePath]];
NSMutableArray *preDatas = nil;
if (preDatas.count == 0) {
preDatas = [NSMutableArray array];
}
else{
preDatas = [NSMutableArray arrayWithArray:fileData];
}
[preDatas addObject:myArray];
[preDatas writeToFile:[self saveFilePath] atomically:YES];
Related
So! I have an NSDictionary that's pulling json out of my database just fine. I also have a mutable array that creates items for my beautiful SESpringboard view. The problem is that, initially, I only had a few items, so I was creating each item manually. But now that I have THOUSANDS of items I want to do something like a "while" loop in php that would just keep creating items until it goes through the whole table.
Here's the code I've got:
Goods *g = [[Goods alloc] init];
g.GID = [dict objectForKey:#"id"];
g.GName = [dict objectForKey:#"name"];
NSLog(#"bk:%#",g.GName);
g.GImg = [dict objectForKey:#"image"];
g.GDesc = [dict objectForKey:#"description"];
NSMutableArray *items = [NSMutableArray array];
[items addObject:[SEMenuItem initWithTitle:g.GName imageName:g.GImg viewController:self removable:NO]];
SESpringBoard *thunderboard = [SESpringBoard initWithTitle:#"Boom" items:items launcherImage:[UIImage imageNamed:#"thor.png"]];
This works absolutely fine… except that what it does is place all the names and all the images one on top of another instead of creating a new item for each result.
If this were php I'd do something like "g.items" and it would just create a new item for each "g" but I'm not sure what to do here. Any help would be appreciated. (I googled but couldn't find anything like this for SESpringBoard items…)
Assuming you parse your json in a variable named allGoods, and that it's an array containing dictionaries representing your "Goods" objects.
You can do this:
NSMutableArray *items = [NSMutableArray array];
for (NSDictionary *dictionary in allGoods) {
[items addObject:[SEMenuItem initWithTitle:[dictionary objectForKey:#"name"] imageName:[dictionary objectForKey:#"image"] viewController:self removable:NO]];
}
SESpringBoard *thunderboard = [SESpringBoard initWithTitle:#"Boom" items:items launcherImage:[UIImage imageNamed:#"thor.png"]];
I removed your usage of "Goods *g", as it looks like you don't need to keep a reference to such an object.
EDIT: here is the 5 items limit you requested
The "MIN" in the for loop is just in case allGoods contains less than 5 items.
for (int i = 0; i < MIN(5, allGoods.count); i++) {
NSDictionary *dictionary = [allGoods objectAtIndex:i];
[items addObject:[SEMenuItem initWithTitle:[dictionary objectForKey:#"name"] imageName:[dictionary objectForKey:#"image"] viewController:self removable:NO]];
}
SESpringBoard *thunderboard = [SESpringBoard initWithTitle:#"Boom" items:items launcherImage:[UIImage imageNamed:#"thor.png"]];
I am not sure what I am missing but i have this for loop below. When I loop through it, the dictionary object gets added to the array like it should each time. But for some reason the next time it loops, it completely replaces all the dictionary object values with the current dictionary value it is looping. So for example I have 5 dictionary objects in my array when it's done looping and all of them have the latest loop values...
NSMutableArray *events = [NSMutableArray array];
NSMutableDictionary *event = [[NSMutableDictionary alloc]init];
NSMutableArray *array = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:#"Update"]];
for (int i = 0; i < [array count]; i = i + 2){
[event setValue:[array objectAtIndex:i+1] forKey:#"Event-Type"];
[event setValue:[array objectAtIndex:i] forKey:#"date"];
[events addObject:event];
}
You would have to allocate a new NSMutableDictionary each iteration of the loop, either at the beginning of each loop (i.e. just move that line into the loop) or when you do addObject you can copy the dictionary using [NSDictionary dictionaryWithDictionary: event];
This is because NSMutableDictionary is an object; It is passed by reference. So you're just putting the same instance of NSMUtableDictionary into your array n times.
You can see this by logging the object at each index of your array at the end, and you can check the memory address to see they're all the same.
Arrays in objective C pass references, not copies. So when you call [events addObject:event] then write to that same event later it gets written over and added newly. Just move the creation of the dictionary inside the for loop and you should be good to go.
You need to alloc init your dictionary inside the loop and also note addition as per Apple Standard always use setObject: forKey: if you are using dictionary. Please refer the below code:-
NSMutableArray *events = [NSMutableArray array];
NSMutableArray *array = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:#"Update"]];
for (int i = 0; i < [array count]; i = i + 2){
NSMutableDictionary *event = [[NSMutableDictionary alloc]init];
[event setObject:[array objectAtIndex:i+1] forKey:#"Event-Type"];
[event setObject:[array objectAtIndex:i] forKey:#"date"];
[events addObject:event];
}
I am working with an application in which i am getting photoID ,which is a string.
I am storing that photoID in array,and again add that array in another array.
Below iS the code::
NSString *photoID;
arr=[[NSMutableArray alloc]initWithCapacity:10];
array=[[NSMutableArray alloc] init];
[array addObject:photoID];
[arr arrayByAddingObjectsFromArray:array];
//number=(int)arr[1];
NSLog(#"arr : %#",arr);
NSLog(#"arr[0] : %#",arr[0]);
NSLog(#"arr[1] : %#",arr[1]);
NSLog(#"Number1 : %#",number1);
NSLog(#"Number : %d",number);
when i tried to access the value of arr[1],my application crashes.
i don't know what am i doing wrong.am i doing wrong to add strings in array,and truing to access unsaved data?
Please help me out.
Thanks in advance
It is because this line: [arr arrayByAddingObjectsFromArray:array]; does nothing to the arr, it only
Returns a new array that is a copy of the receiving array with the
objects contained in another array added to the end.
You should replace it with [arr addObjectsFromArray:array];. And also, you only have 1 element in arr which is at index 0, so the arr[1] should crash but arr[0] should work.
First array should be NSArray if you want to arrayByAddingObjectsFromArray or addObjectsFromArray
NSArray *array1=[[NSArray alloc]initWithObjects:#"1",#"2",#"3", nil];
NSMutableArray *array2=[[NSMutableArray alloc]init];
[array2 addObjectsFromArray:array1];
NSLog(#"%d",array2.count);
You can also use like this:
NSMutableArray *innerArray = [[NSMutableArray alloc] initWithObjects:#"1",#"2",#"3", nil];
NSMutableArray *outerArray = [NSMutableArray array];
for(int i=0;i<=innerArray.count;i++)
{
[outerArray addObject:innerArray];
}
I am in my IOS application in which i am getting ID from server which i am saving in string and then add strings in NSMutableArray.I am not getting perfect method by which i can add the strings in array and use the array outside the scope.
Here is my code Please help me out::
- (void)flickrAPIRequest:(OFFlickrAPIRequest *)inRequest didCompleteWithResponse:(NSDictionary *)inResponseDictionary
{
NSMutableArray *array=[[NSMutableArray alloc]init];
i=0;
NSLog(#"%s %# %#", __PRETTY_FUNCTION__, inRequest.sessionInfo, inResponseDictionary);
if (inRequest.sessionInfo == kUploadImageStep)
{
snapPictureDescriptionLabel.text = #"Setting properties...";
NSLog(#"%#", inResponseDictionary);
NSString* photoID =[[inResponseDictionary valueForKeyPath:#"photoid"] textContent];
flickrRequest.sessionInfo = kSetImagePropertiesStep;
// for uploading pics on flickr we call this method
[flickrRequest callAPIMethodWithPOST:#"flickr.photos.setMeta" arguments:[NSDictionary dictionaryWithObjectsAndKeys:photoID, #"photo_id", #"PicBackMan", #"title", #"Uploaded from my iPhone/iPod Touch", #"description", nil]];
[self.array addObject:photoID];
arr=array[0];
counterflicker++;
NSLog(#" Count : %lu", (unsigned long)[array count]);
}
How can i add the photoID(Strings) in the array?
Please help me out..
for adding NSString in NSMutableArray is like this
NSString *str = #"object";
NSMutableArray *loArr = [[NSMutableArray alloc] init];
[loArr addObject:str];
In your code Why are you using self.array ? just write like this. [array addObject:photoID];
self keyword is used for global variables but here in your code
"array" is a local variable .So need of self.array
[array addObject:photoID];
Before adding check that photoID is nil or not
if (photoID.length > 0) {
[array addObject:photoID];
}
I observe that in your code. you declare mutable array in local scope.
So just use
[array addObject:photoID];
Instead of
[self.array addObject:photoID];
May be you are create property for this array with same name, then you need to alloc it.
If you create a property for this then remove local declaration and alloc array like this.
self.array=[[NSMutableArray alloc]init];
and then use
[self.array addObject:photoID];
i have two nsmutableArray . Arr_jsondata and second is tempArray.
Already Arr_jsondata contain the data from json link and display in tableview .
i want to add the tempArray data into Arr_jsondata and reload the table using Arr_jsondata , because tableview delegate is also used this array to display the data in tableview .
but its always give me an error when i add temp array data into arr_jsondata .
for (int i=0; i<[Temp_arr_JsonData count]; i++)
{
NSString *str_brandname = [[Temp_arr_JsonData objectAtIndex:i] valueForKey:#"storebrand"];
NSLog(#"%#",str_brandname);
NSObject *myNewObject = [[NSObject alloc] init];
if ([str_brandname isEqualToString:#"Nike"])
{
NSLog(#"Data matched");
c++;
myNewObject = [Temp_arr_JsonData objectAtIndex:i];
[temparray addObject:myNewObject];
}
}
// arr_JsonData=temparray;
[[arr_JsonData arrayByAddingObjectsFromArray:temparray] mutableCopy];
NSLog(#"%#",temparray);//display all nike related data
NSLog(#"%#",arr_JsonData);//display null array .
[self.tableView reloadData];
[sender setSelected:YES];
in last i want only tempdata into Arr_jsondata ..... what can i do ?
Just add objects from array. See this apple's doc
if (arr_JsonData.count > 0)
[arr_JsonData addObjectsFromArray: (NSArray*)temparray];
else
arr_JsonData = [NSMutableArray arrayWithArray:(NSArray*)temparray]
You can try this
[arr_JsonData addObjectsFromArray:tempArray];
I think arr_JsonData is not NSMutableArray actually which can be judged from the exception description you listed in the answer. Try this:
arr_JsonData = [NSMutableArray arrayWithArray:arr_JsonData];
[arr_JsonData addObjectsFromArray: temparray];
Try using this:
NSMutableArray *ar = [NSMutableArray alloc] initWithArray:ar1];
Just have to initialize array with other array and it will have all contents from other array.
Or this one:
NSMutableArray *ar = [NSMutableArray alloc] initWithArray:ar1 copyItems:YES];
mutableCopy is defined for NSArray not for NSMutableArray
if ([arr_JsonData count] > 0)
{
[arr_JsonData addObjectsFromArray: temparray];
}