how to do shift and push operation in objective c - ios

I have an array [1,2,3,4]
I need to continously shift and push one element into the same array
so that the first variable values will be 1,2,3,4,1,2,3,4,...
and second variable values will be 2,3,4,1,2,3,4,1,...
How to do that??

Use NSMutableArray like:
1) to get the object at the first position:
object = [nameArray firstObject];
[nameArray removeObjectAtIndex:0];
2) then insert it in last position:
[nameArray addObject:object];
p.s. remember to always add some sanity checks.

You would need
- exchangeObjectAtIndex:withObjectAtIndex:
Exchanges the objects in the array at given indices.
See Documentation here
Example
NSMutableArray *array = [NSMutableArray array];
[array setArray:#[#"Eezy",#"Tutorials",#"Website"]];
[array exchangeObjectAtIndex:0 withObjectAtIndex:2];
NSLog(#"%#",array);
NSMutableArray *obj = [NSMutableArray arrayWithObjects:#"1",#"2",#"3",nil];
[obj exchangeObjectAtIndex:0 withObjectAtIndex:obj.count - 1];
NSLog(#"%#",obj);

Related

Adding NSDictionary to an array

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];
}

Looping thru NSArray of NSString logic

I need help with the following:
I have an NSArray with NSStrings, I want to loop thru these strings and find a matching string, when match is found the strings after this match will be extracted into an NSDictionary until a certain other match is hit.
Here is an example:
NSArray *array = #[#"Fruit",#"Apple",#"Vegtable",#"Tomato",#"Fruit",#"Banana",#"Vegtable",#"Cucumber"];
So I want to loop thru this array and split it in 2 arrays one for fruit and one for vegetable.
Anyone can help with the logic?
Thanks
This is probably the simplest way to solve the problem:
NSArray *array = #[#"Chair",#"Fruit",#"Apple",#"Orange",#"Vegetable",#"Tomato",#"Fruit",#"Banana",#"Vegetable",#"Cucumber"];
NSMutableArray *fruitArray = [NSMutableArray array];
NSMutableArray *vegetableArray = [NSMutableArray array];
NSMutableArray *currentTarget = nil;
for (NSString *item in array)
{
if ([item isEqualToString: #"Fruit"])
{
currentTarget = fruitArray;
}
else if ([item isEqualToString: #"Vegetable"])
{
currentTarget = vegetableArray;
}
else
{
[currentTarget addObject: item];
}
}
In one iteration over the array, you just keep adding items to a result array using a pointer to one of two result arrays according to the last occurrence of the #"Fruit" or #"Vegetable" string.
This algorithm ignores all items before the first occurrence of the #"Fruit" or #"Vegetable" string, because the currentTarget is initialized to nil, which ignores the addObject: messages. If you want different behaviour, just change the initialization.
You said you wanted the results in a NSDictionary, but didn't specify what should be the key. If you want one NSDictionary with two keys, Fruit and Vegetable, and values NSArrays containing the items, just use the arrays previously created:
NSDictionary *dict = #{ #"Fruit": fruitArray, #"Vegetable": vegetableArray };
PS: You have a typo in your example, Vegtable instead of Vegetable. I corrected it in my code, so keep it in mind.
If I completely understand you:
NSArray *array = #[#"Fruit",#"Apple",#"Vegtable",#"Tomato",#"Fruit",#"Banana",#"Vegtable",#"Cucumber"];
NSMutableArray *fruits = [NSMutableArray array];
NSMutableArray *vegtables = [NSMutableArray array];
for (NSInteger i = 0; i < array.count; ++i){
if ([array[i] isEqualToString:#"Fruit"]){
++i;
[fruits addObject:array[i]];
}
else if ([array[i] isEqualToString:#"Vegtable"]){
++i;
[vegtables addObject:array[i]];
}
}

Retriving Array values from the NSMutableArray in IOS

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];
}

How to dynamically create a number of NSMutableArray(s)?

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];

Objective C: Sort Two Dimensional Array

I have an array of arrays. The contained array's first elements are all NSDate objects. I would like to sort the array containing the arrays in order from most recent to least. For some reason, the below sorting algorithm results in an infinite loop. Can anyone help me out? Thank you.
Best...SL
//array is the array containing all of the other arrays(that have NSDates as their first elements)
//temp is the new array being added to the end of the array, to later be sorted into the correct position.
[array addObject:temp];
NSMutableArray *tempArray;
for (int i=0; i<[array count]; i++)
{
NSDate *session1, *session2;
session1 = [[array objectAtIndex:i] objectAtIndex:0];
session2 = [[array objectAtIndex:[array count]-1] objectAtIndex:0];
if([session1 compare:session2] == NSOrderedDescending)
{
tempArray = [array objectAtIndex:i];
[array insertObject:[array objectAtIndex:[array count]-1] atIndex:i];
[array insertObject:tempArray atIndex:[array count]-1];
}
}
This results in an infinite loop because, in every step, you're inserting two more values into the array. Thus your array is growing faster than you are traversing it. I'm assuming you meant to swap the values.
In any case, a much simpler and more efficient sort is to use the built-in sorting capabilities:
// NSArray *sortedArray, with the unsorted 'array' pulled from some other instance
sortedArray = [array sortedArrayUsingComparator:^(id a, id b) {
return [[b objectAtIndex:0] compare:[a objectAtIndex:0]];
}];
If array is mutable and you want to sort it in place:
[array sortUsingComparator:^(id a, id b) {
return [b[0] compare:a[0]];
}];
If array is immutable or you want to leave it alone and make a sorted copy:
NSArray *sortedArray = [array sortedArrayUsingComparator:^(id a, id b) {
return [b[0] compare:a[0]];
}];

Resources