iOS Cocoa Touch Add Object to NSArray - ios

I have an NSArray that has to be an array for portions of the project so nothing will change it. I need to add an object to the array. The method I used was to convert to an NSMutableArray, add the object, and then convert back to an NSArray. The method:
- (void)addAdj:(NSString *)obj{
NSMutableArray *ary = [self.adj mutableCopy];
[ary addObject:obj];
self.adj=[ary copy];
for(int i = 0; i<[self.adj count]; i++){
NSLog(#"%#, ", [self.adj objectAtIndex:i]);
}
}
The for loop and log statement are included to print the array but it does not print anything at all. I have seen similar questions but people always tell the OP to just use an NSMutable array from the start. I'd like to know why this bit of code does not work as is. In advance Thanks!

May be you have already forgot to initialize self.adj in viewDidload. You try to add below code to viewDidload:
self.adj = [[NSArray alloc]init];
Or you can show code in your viewDidload. I will be more help.

Related

NSMutableArray: data missing when init with an Array

As the screenshot showing, anyone who knows what's the problem of it? Thanks for kindly help!
In you for look just put codeList and your problem will be fixed.
check this I modified your method.
-(NSArray *) checkVisibleCode:(NSArray *) codeList{
NSMutableArray *list = [NSMutableArray arrayWithArray:codeList];
for (NSString *code in codeList) {
if (![self.codeMapping.allKeys containsObject:code]) {
[list removeObject:code];
}
}
return list;
}
You are removing object from the Array you're iterating on.
It's a bad practice that can lead to mistakes like this.
You simply have to replace
for (NSString *code in list)
with :
for (NSString *code in codeList)
Don't delete objets from an array or dictionary or any collection set while you're iterating on it .
Keep the indexes you want to delete when iterating then remove all the objets. You can use indexesOfObjectsPassingTest method :
NSMutableArray * list = [NSMutableArray arrayWithArray:codeList];
NSIndexSet * indexesToRemove = [list indexesOfObjectsPassingTest:^BOOL(NSString *code, NSUInteger idx, BOOL *stop) {
return [self.codeMapping.allKeys containsObject:code];
}];
[list removeObjectsAtIndexes:indexesToRemove];
You should do this using indexesOfObjectsPassingTest and objectsAtIndexes: Even if you follow for example Anbu's reply to make your code work, this code runs in O (n^2). Do it with a list of 100,000 objects where every second object gets removed, and your app dies a sad death because it runs out of CPU time.

Capitalized NSArray of Strings?

I have an NSarray called array. And it look like this
array = #[#"one", #"two", #"three"];
I want this array to be capitalized. What is the best way to go about this. I can only think of making an NSMutableArray called mutableArray.
And do something like this
for(int i = 0; i < array.lenght; i++) {
self.mutableArray = addObject:[array[i] capitalizedString];
}
Or is there another better way?
The magic method you are looking for does in fact exist.
NSArray *array = #[#"one", #"two", #"three"];
NSArray *capArray = [array valueForKeyPath:#"capitalizedString"];
SWIFT
You Can use map
let array = ["one", "two", "three"]
let upercaseArray = array.map({$0.uppercased()})
now you have upercaseArray like ["ONE","TWO","THREE""]
What you really want is a sort of transform method, which takes an array and a selector, then returns an array of the results of performing that selector on each object. Unfortunately that doesn't exist in vanilla objective-C.
Your approach is generally fine, but I would be careful of two points. Firstly, make sure you create the NSMutableArray with the capacity of the NSArray you are copying, as this will avoid any reallocation overhead as you add objects to it. Secondly, you might want to copy the mutable array so you end up with an immutable NSArray as the final result.
So I would use something like this:
- (NSArray *)capitalizeStringArray:(NSArray *)array {
// Initialize tempArray with size of array
NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:array.count];
for (NSString *str in array) {
[tempArray addObject:[str capitalizedString]];
}
return [tempArray copy]; // convert back to NSArray]
}
You can convert this to a category method on NSArray if you like, and generalize it to use other selectors if you wish.
There's about a gazillion ways to handle this. For small arrays, pick whichever you find easier to understand.
I'd probably use code like this:
- (NSMutableArray *) capitalizedArrayFromArrayOfStrings: (NSArray*) array;
{
NSMutableArray *result = [NSMutableArray arrayWithCapacity: array.count];
for (NSString *string in array)
{
if ([string isKindOfClass: [NSString class]]
[result addObject: [string capitalizedString];
}
}
Creating your array with the correct capacity at the beginning enables the array to allocate enough space for all it's future elements and saves it having to allocate more space later.
Using for..in fast enumeration syntax is more efficient than using array indexing, but for short arrays the difference is small. The code is also simpler to write and simpler to read, so I prefer that syntax where possible.
As Alex says, you could also create a category method on NSArray that would return a capitalized version of your array, or even a category on NSMutableArray that would replace the strings in the array "in place".
Works like charm.
NSString *myString = YOUR_ARRAY.uppercaseString;
[myNSMutableArray addObject:myString];

How to Make Array of Float Data Type in ios

I want to make array of float type.
Anybody can help me?
NSArray *arrOfFloat = [[[NSArray alloc]initWithObjects:[12.2, 23.44], nil]];
But i want to make array dynamically.
But i want to make array dynamically.
This means you'll have to use an NSMutableArray.
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:#1.1];
[array addObject:#2.2];
...
You also can't add primitives to an array. You'll need to add objects. Notice the # I added before the numbers. This creates number literals.
If you have the floats you want to add as variables, you can auto boxing like this:
[array addObject:#(myFloatVariable)];
Use NSMutableArray class instead of a NSArray (this is a subclass of it), this way, within your code, you will be able to call :
NSMutableArray *yourArray = [NSMutableArray new];
[yourArray addObject:#(1.0f)];
NSArraycan only store objects, so in your case you would have to store your float as NSNumber. If you want to store objects dynamically, thus adding or removing them to an NSArray you have to use the mutable object type called NSMutableArray.
You'll need to wrap your float's in an NSNumber:
[NSNumber numberWithFloat:12.2];
If you're dynamically adding elements to an array, you need to use NSMutableArray.
NSMutableArray *array = [NSMutableArray array];
[array addObject:[NSNumber numberWithFloat:12.2]];
You can use NSMutableArray for example named arrOfFloat and add this :
[arrOfFloat addObject:[NSNumber numberWithFloat:3.5]];
[arrOfFloat addObject:[NSNumber numberWithFloat:23.44]];
Hope, It will may helpful to you.

How can I move the values in NSMutableArray to NSArray

I have an array of recommendedcar IDs, and another array of allcar IDs. From this, I have to take the recommendedcar images. First, I check whether the recommended carid is in my allcar id; if it is, I select the corresponding car images, and store them into NSArray.
This is the code I am using.
for (int i=0;i<[listOfCarId count];i++) {
for (int j=0;j<[_allCarID count];j++) {
tempAllCarId=[_allCarID objectAtIndex:j];
tempRecommendedCarId=[listOfCarId objectAtIndex:i];
if ([tempRecommendedCarId isEqualToString:tempAllCarId]) {
_recommendedCarImage=[_allCarImages objectAtIndex:j];
NSLog(#"finalImage%#",_recommendedCarImage);
}
}
}
_recommendedcarImage is NSMUtableArray; I want a NSArray. How can I convert it to a NSArray?
How can i replace the "_recommendedCarImage " with an NSArray?? Currently _recommendedCarImage is a mutable array.
Polymorphism. Since NSMutableArray is a subclass of NSArray, you can use it anywhere an NSArray is expected. You don't have to do anything.
Now its working,What i did is , I just copy the contents of Mutable array to NSarray
recommendedArray=[_recommendedCarImage copy];
An NSMutableArray is an NSArray already (as it's a subclass of NSArray), still you can do:
NSArray *array = [NSArray arrayWithArray:mutableArray];

remove object from NSArray

How can I remove an object from a reversed NSArray.
Currently I have a NSMutableArray, then I reverse it with
NSArray* reversedCalEvents = [[calEvents reverseObjectEnumerator] allObjects];
now I need to remove at item from reversedCalEvents or calEvents and automatically refresh the table the array is displayed in based on conditions.
i.e.
if(someInt == someOtherInt){
remove object at index 0
}
How can I do this? I cannot get it to work.
Here's a more functional approach using Key-Value Coding:
#implementation NSArray (Additions)
- (instancetype)arrayByRemovingObject:(id)object {
return [self filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"SELF != %#", object]];
}
#end
You will need a mutable array in order to remove an object. Try creating reversedCalEvents with mutableCopy.
NSMutableArray *reversedCalEvents = [[calEvents reverseObjectEnumerator] allObjects] mutableCopy];
if (someInt == someOtherInt)
{
[reversedCalEvents removeObject:object];
}
NSArray is not editable, so that you cannot modify it. You can copy that array to NSMutableArray and remove objects from it. And finally reassign the values of the NSMutableArray to your NSArray.
From here you will get a better idea...
NSArray + remove item from array
First you should read up on the NSMutableArray class itself to familiarize yourself with it.
Second, this question should show you an easy way to remove the objects from your NSMutableArray instance.
Third, you can cause the UITableView to refresh by sending it the reloadData message.
you can try this:-
NSMutableArray* reversedCalEvents = [[[calEvents reverseObjectEnumerator] allObjects] mutableCopy];
[reversedCalEvents removeLastObject];

Resources