how to add the element in the array using the for loop in objective-c? - iphone

is this the right way to do the same?
nsmutablearray *myarray1 //have some data in it
for (int i=0;i< [myarray1 count]; i++)
{
myArray2 = [NSMutableArray array];
[myArray2 addObject:i];
}
and how can i print this value of myarray2.

If you are trying to copy element of one array to other array then use following code:
NSMutableArray *secondArray = [NSMutableArray arrayWithArray:firstArray];
If you want to print element value then depending upon data stored in your array you can print element.
i.e if array contains string object then you can print like this:
for(int i=0;i<secondArray.count;i++)
{
NSLog(#"Element Value : %#",[secondArray objectAtIndex:i]);
}
if array contains any user define object then you can print like this:
for(int i=0;i<secondArray.count;i++)
{
UserDefineObject *obj = [secondArray objectAtIndex:i];
NSLog(#"Element Value with property value: %#",obj.property);
}

The easiest way to create a new array containing the same elements as the old array is to use NSCopying or NSMutableCopying.
NSArray* myArray2 = [myArray1 copy]; // myArray2 is an immutable array
NSMutableArray* myArray3 = [myArray1 mutableCopy]; // myArray3 is an mutable array
If you want to print the contents of an array for debugging purposes:
NSLog(#"myArray2 = %#", myArray2);
If you want prettier printing for a UI, you'll need to iterate through as others have suggested.

Related

error in array cleaning method

I am attempting to use this array cleaning method, and there seems to be an error. I can't spot it, I know the array goes in with 3116 items, comes out with 3116 (and I know for a fact there are three duplicates.
Please advice, thanks!
-(NSArray*) removeDuplicates:(NSArray*)inputArray{
NSMutableArray *arrayToClean = [NSMutableArray arrayWithArray:inputArray];
for (int i =0; i<[arrayToClean count]; i++) {
for (int j=(i+1); j < [arrayToClean count]; j++) {
if ([[arrayToClean objectAtIndex:i] isEqual:[arrayToClean
objectAtIndex:j]]) {
[arrayToClean removeObjectAtIndex:j];
j--;
}
}
}
NSArray *arrayToReturn = [NSArray arrayWithArray:arrayToClean];
return arrayToReturn;
}
NSSet will make this a lot easier:
-(NSArray *)removeDuplicates:(NSArray *)inputArray {
NSSet *unique = [NSSet setWithArray:inputArray];
return [unique allObjects];
}
Please note that a set has no guaranteed order. If you need the objects in the array to be in a specific order then you should sort the resulting array as needed.
It may also be appropriate to use an NSSet instead of the original array, then you don't need to worry about duplicates at all. But this depends on the other needs of your array.
Hey You can use another alternative for this.You can use the NSSet here for this task.
NSSet declares the programmatic interface for static sets of distinct objects
You can use sets as an alternative to arrays when the order of elements isn’t important and performance in testing whether an object is contained in the set is a consideration—while arrays are ordered, testing for membership is slower than with sets.
You Just need To call below method.
-(NSArray *)removeDuplicates:(NSArray *)inputArray {
NSSet *finalData = [NSSet setWithArray:inputArray];
return [finalData allObjects];
}
If really face any problem in above way of cleaning ducplicates then you can try another Alterantive.
-(NSArray *)removeDuplicates:(NSArray *)inputArray {
NSMutableArray *inputArray1=[NSMutableArray arrayWithArray:inputArray];
NSMutableArray *finalARray=[[NSMutableArray alloc]init];
for (id obj in inputArray1)
{
if (![finalARray containsObject:obj])
{
[finalARray addObject: obj];
}
NSLog(#"new array is %#",finalARray);
}
return finalARray;
}
I hope it may help you ...
Here is a helper function I had in a previous project to do the exact same thing
- (NSMutableArray *)removeDuplicates:(NSMutableArray *)sortedArray{
NSMutableSet* valuesAdded = [NSMutableSet set];
NSMutableArray* filteredArray = [[NSMutableArray alloc] init];
NSString* object;
/* Iterate over the array checking if the value is a member of the set. If its not add it
* to the set and to the returning array. If the value is already a member, skip over it.
*/
for (object in sortedArray){
if (![valuesAdded member:object]){
[valuesAdded addObject:object];
[filteredArray addObject:object];
}
}
return filteredArray;
}

Empty NSMutableArray , not sure why

Ok so I populate the array like this:
NSMutableArray *participants;
for(int i = 0; i < sizeofpm; i++){
NSDictionary *pmpart_dict = [pm_participants objectAtIndex:i];
NSString *pmpart_email = [pmpart_dict objectForKey:#"email"];
NSString *pmpart_email_extra = [#"pm" stringByAppendingString:pmpart_email];
[participants setValue:pmpart_email forKey:pmpart_email_extra];
NSLog(#"%#", participants);
}
sizeofpm is 1. that is using count. to get the number of values in the array. How can i store values to that array? It doesnt seem to be working. Thanks!
you need to alloc it first. Try to change the first line to:
NSMutableArray* participants = [[NSMutableArray alloc] init];
also using setValue:forKey: wont work with an NSMutableArray as an array has no key.
Try using [participants addObject:pmpart_email];.
You don't create the array, you just declare it.
NSMutableArray *participants = [NSMutableArray array];
After that, setValue:forKey: will not add objects to an array. You need addObject::
[participants addObject:pmpart_email];
There is no key.
You are assigning a value to an NSMutableArray *participants like how you assign values to an NSDictionary object. To assign values to NSMutableArray you can call - (void)addObject:(id)anObject
So, I as some of the other answer have stated, you're missing your initializer for participants. However, judging by your use of setValue:forKey:, and how you appear to be structuring your data, you're not looking for NSMutableArray, but instead NSMutableDictionary. Arrays are simply lists, whereas dictionaries maintain key-value relationships, which you appear to be attempting to leverage.
Try this:
// some classes provide shorthand for `alloc/init`, such as `dictionary`
NSMutableDictionary *participants = [NSMutableDictionary dictionary];
for(int i = 0; i < sizeofpm; i++){
NSDictionary *pmpart_dict = [pm_participants objectAtIndex:i];
NSString *pmpart_email = [pmpart_dict objectForKey:#"email"];
NSString *pmpart_email_extra = [#"pm" stringByAppendingString:pmpart_email];
[participants setValue:pmpart_email forKey:pmpart_email_extra];
NSLog(#"%#", participants);
}
This will give you a dictionary in the form of
{
pmpart_email_extra: pmpart_email
}

Initialize an NSArray with the numbers in a sequential manner when the count of the array is known

I want to initialize an NSArray with numbers starting from 0,1,2,3... I know the count of the array. For example:
I have an array that needs to be initialized with 5 (count) as capacity. Now I want to initialize this array with 0,1,2,3,4 and I need to initialize it dynamically.
If the count of the array is 10, I need to initialize the array with 0,1,2,3,4,5,6,7,8,9 at respective indexes. The problem is that count of the array changes dynamically and I need to initialize it accordingly.
Can someone suggest me any idea on how to implement this?
NSMutableArray* arrOfObject = [[NSMutableArray alloc] init];
for(int i=0; i< [arr count]; i++)
{
arrOfObject addObject:[NSNumber numberWithInt:i];
}
Initialize a mutable array. Then add the numbers in a loop. Optionally initialize a new non-mutable array with your mutable one using arrayWithArray:.
int count = 5;//suppose this you want
NSMutableArray *array = [NSMutableArray array];
for(int i=0 ; i< count; i++) {
[array addObject:[NSNumber numberWithInt:i];
}
You just need to pass the count from where you want it, and it will dynamically generate your desired array.
Use NSMutableArray then just add as many as you need
int count = 10;
NSMutableArray *array = [[NSMutableArray alloc] init];
for (int i=0;i<count;i++) {
[array addObject:[NSNumber numberWithInt:i]];
}

Trying to add many arrays to one NSMutableArray

I'm Trying here to add many arrays to one NSMutableArray
Actually am adding the same array with different values Many Times to one NSMutable Array
this the code:
NSMutableArray* wordsArray =[[NSMutableArray alloc] init ];
NSMutableArray* meaningsArray=[[NSMutableArray alloc]init];
NSMutableArray* wordsArrayTemp=[[NSMutableArray alloc]init];
NSMutableArray* meaningsArrayTemp=[[NSMutableArray alloc]init ];
NSMutableArray* allWords =[[NSMutableArray alloc]initWithCapacity:2];
NSMutableArray* allMeanings=[[NSMutableArray alloc]initWithCapacity:2];
for(int i=0;i<2;i++)
{
int wordsCounter=0;
[wordsArrayTemp removeAllObjects];
[meaningsArrayTemp removeAllObjects];
for(NSString *tmp in wordsArray)
{
NSString *meaning =[meaningsArray objectAtIndex:wordsCounter++];
subtmp= [ tmp substringWithRange:NSMakeRange(0,1)];
if([currentTable isEqualToString:#"arabicToEnglish"])
{
if([subtmp isEqualToString:[arabicLetters objectAtIndex:i]])
{
[wordsArrayTemp addObject:tmp];
[meaningsArrayTemp addObject:meaning];
}
}
else
if([subtmp isEqualToString:[englishLetters objectAtIndex:i]])
{
[wordsArrayTemp addObject:tmp];
[meaningsArrayTemp addObject:meaning];
}
}
[allWords insertObject:wordsArrayTemp atIndex:i];
// [allWords addObject: wordsArrayTemp];
[allMeanings addObject:meaningsArrayTemp];
NSLog(#"all words count%i",[[allWords objectAtIndex:i] count]);
}
The Problem :
The supposed behavior here is to have 2 different values in the allWords array .
But what Actually happens is that the 2 values filled with the same value with the last index Value.
I mean [allWords objectAtIndex:0] should have 2000 object and [allWords objectAtIndex:1] should have 3000 ,but what happens that they both have 3000 object !!
what am I missing here?!!
thnx
when you add an object to an array the object is not copied. You just save its memory address.
Basically you added the same temporary array to the parent array. And you did all your array manipulations to the same array.
Maybe this piece of unrolled loop code will make it a little bit clearer.
// create new array on a specific memory address. let's say this address is 0x01
NSMutableArray* wordsArrayTemp=[[NSMutableArray alloc]init];
// first iteration of your loop
// remove all objects from array at memory address 0x01
[wordsArrayTemp removeAllObjects];
// add objects to the array at address 0x01
[wordsArrayTemp addObject:tmp];
// insert array (still at address 0x01) to the parent array
[allWords insertObject:wordsArrayTemp atIndex:i];
// your allWords array now looks like this: {array#0x01}
// second iteration of your loop
// remove all objects from array at memory address 0x01!!! (still the same array as in the first iteration)
// since it's the same array all objects from the array at [allWords objectAtIndex:0] are removed too
[wordsArrayTemp removeAllObjects];
// add objects to the array at address 0x01
[wordsArrayTemp addObject:tmp];
// insert array (still at address 0x01) to the parent array
[allWords insertObject:wordsArrayTemp atIndex:i];
// your allWords array now looks like this {array#0x01, array#0x01}
the solution is pretty easy.
At the beginning of the for-loop instead of removing allObjects from the array create new arrays.
Just replace
[wordsArrayTemp removeAllObjects];
[meaningsArrayTemp removeAllObjects];
with
wordsArrayTemp = [NSMutableArray array];
meaningsArrayTemp = [NSMutableArray array];
Try to add one array simutaneously :
[[allWords array] addObject:wordsArray.array];
Hope it'll help
Try this:-
[allWords insertObject:[wordsArrayTemp copy] atIndex:i];
It should work.

how to implement Multidimention array

I want to use a multidimensional array. Can any one explain how to use that in an iPhone app? I'm new to Objective-C.
Here's what I'm trying to do:
I am spliting the main string on the basis of seprator and storing in an array.
replacing some content of this array's each elements with new substrings and new values are storing in an new array.
want to again split the each element of new array with a new seprator and want to store this new value in new array
assuming this will be eassy by using multidimention.
Thanks,
Aaryan
(the code I have so far)
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableArray *arrSeprate = [[NSMutableArray alloc]init];
NSString *temp;
// it is a mysql query//
insertqry = #"INSERT INTO `userDecks` VALUES (1,2,618),(1,3,1471),(1,4,0),(1,5,0),(1,6,7784),(1,11,0),(1,12,469),(1,13,0),(1,16,0),(1,17,113),(1,18,0),(1,19,752),(1,20,60),(1,21,0),(1,30,0),(1,31,0),(1,32,159),(1,34,129),(1,46,143),(1,47,0),(1,53,105),(1,55,456),(1,65,0),(1,66,127),(1,67,131)";
//step-1 ----------begin--------
NSArray *listItems = [insertqry componentsSeparatedByString:#"),"];
//step-1 ----------end--------
int i=0;
//step-2 ----------begin--------
for (i = 1; i<[listItems count]; i++)
{
temp = [listItems objectAtIndex:i];
temp = [temp stringByReplacingOccurrencesOfString:#"(" withString:#"INSERT INTO `userInvitation` VALUES ("];
[arrSeprate addObject:temp];
}
//step-2 ----------end-------------
//step-3 ----------begin--------this will use the for loop to ll elemts of previous array
NSString *middleqry = [arrSeprate objectAtIndex:0];
NSArray *ItemsArray = [middleqry componentsSeparatedByString:#","];
NSLog(#"%#",ItemsArray);
}
Very easily, you can just add the itemsArray into the mutable array you created. This achieves the same as a multi-dimensional array. Alternatively, you can just use C multi-dimensional arrays with pointers.