How to do that without having to "scroll" the entire given array with a "for" loop?
The best I can come up with is:
NSMutableArray *replacementArray = [NSMutableArray array];
[originalArray enumerateObjectsUsingBlock:
^(id obj, NSUInteger index, BOOL *stop)
{
[replacementArray addObject:[[obj mutableCopy] autorelease]];
}
];
Which more or less just tells the originalArray to construct the for loop for you. And if anything it's more work than:
NSMutableArray *replacementArray = [NSMutableArray array];
for(id obj in originalArray)
[replacementArray addObject:[[obj mutableCopy] autorelease]];
Since nobody seems to agree with my comment that this is a duplicate of Better way to convert NSArray of NSNumbers to array of NSStrings, here's the same answer again:
NSArray * arrayOfMutableStrings = [arrayOfStrings valueForKey:#"mutableCopy"];
From the docs:
valueForKey:
Returns an array containing the results of invoking
valueForKey: using key on each of the array's objects.
- (id)valueForKey:(NSString *)key
Parameters
key The key to retrieve.
Return Value
The value of the retrieved key.
Discussion
The returned array contains NSNull elements for each object that returns nil.
I wrote a dictionary method on NSArray to be able to write cleaner functional code
-(NSArray *)arrayByPerformingBlock:(id (^)(id))performBlock
{
NSMutableArray *array = [NSMutableArray array];
for (id element in self)
[array addObject:performBlock(element)];
return [NSArray arrayWithArray:array];
}
usage:
arrayWithStrings = [arrayWithStrings arrayByPerformingBlock:^id(id element) {return [[element mutableCopy] autorelease];}];
This was inspired by list comprehensions I know from Python. I also wrote versions of this methods with testing. See my arraytools.
Related
How to do that without having to "scroll" the entire given array with a "for" loop?
The best I can come up with is:
NSMutableArray *replacementArray = [NSMutableArray array];
[originalArray enumerateObjectsUsingBlock:
^(id obj, NSUInteger index, BOOL *stop)
{
[replacementArray addObject:[[obj mutableCopy] autorelease]];
}
];
Which more or less just tells the originalArray to construct the for loop for you. And if anything it's more work than:
NSMutableArray *replacementArray = [NSMutableArray array];
for(id obj in originalArray)
[replacementArray addObject:[[obj mutableCopy] autorelease]];
Since nobody seems to agree with my comment that this is a duplicate of Better way to convert NSArray of NSNumbers to array of NSStrings, here's the same answer again:
NSArray * arrayOfMutableStrings = [arrayOfStrings valueForKey:#"mutableCopy"];
From the docs:
valueForKey:
Returns an array containing the results of invoking
valueForKey: using key on each of the array's objects.
- (id)valueForKey:(NSString *)key
Parameters
key The key to retrieve.
Return Value
The value of the retrieved key.
Discussion
The returned array contains NSNull elements for each object that returns nil.
I wrote a dictionary method on NSArray to be able to write cleaner functional code
-(NSArray *)arrayByPerformingBlock:(id (^)(id))performBlock
{
NSMutableArray *array = [NSMutableArray array];
for (id element in self)
[array addObject:performBlock(element)];
return [NSArray arrayWithArray:array];
}
usage:
arrayWithStrings = [arrayWithStrings arrayByPerformingBlock:^id(id element) {return [[element mutableCopy] autorelease];}];
This was inspired by list comprehensions I know from Python. I also wrote versions of this methods with testing. See my arraytools.
My challenge this week has been to come to terms with blocks in objective-c. There is something about the syntax that does my head in. Getting there.
I have the following code to achieve a merge of two arrays in a specific way (see comment in code below).
NSArray *keys = #[#"name", #"age"];
NSArray *data = #[
#[#"mark", #"36 years"],
#[#"matt", #"35 years"],
#[#"zoe", #"7 years"]
];
// desired outcome is
// # { #"name" : #[#"mark", #"matt", #"zoe"],
// #"age" : #[#"36 years", #"35 years", #"7 years"]
// }
NSMutableArray *mergedData = [[NSMutableArray alloc] initWithCapacity:keys.count];
for (NSString *key in keys) {
NSLog(#"key: %#", key);
NSInteger keyIndex = [keys indexOfObject:key];
NSMutableArray *dataItemsForKey = [[NSMutableArray alloc] initWithCapacity:data.count];
for (NSArray *row in data) {
// double check the array count for row equals the expected count for keys - otherwise we have a 'match up' issue
if (row.count == keys.count) {
[dataItemsForKey addObject:[row objectAtIndex:keyIndex]];
}
}
[mergedData addObject:[NSDictionary dictionaryWithObject:dataItemsForKey forKey:key]];
}
NSLog (#"mergedData: %#", mergedData);
While this code works fine, in the interest of my challenge and learning, I was wondering if there is a more 'elegant' (aka less code, easier to read) way to do this using enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) ??
I can't quite see a way to make it work, but in the interests of self-education, wonder if those more learned in blocks and arrays may have a more elegant solution.
The first issue that I notice is that you are asking for the index of the current object while enumerating the array. This is a waste of operations, because at every loop iteration you have to look over all array elements (potentially O(N)) to find where the object is.
You could instead do this:
for(NSUInteger i=0; i<keys.count; i++)
{
NSString* key= keys[i];
<Rest of the code>
}
Or just keep track of the index manually incrementing it:
NSUInteger i=0;
for (NSString *key in keys)
{
<Your code>
i++;
}
Or like you wanted, with enumerateObjectsUsingBlock:, which is IMO the most elegant way to do it in this case. Here is an example:
NSMutableDictionary* dict=[NSMutableDictionary new];
[keys enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
NSMutableArray* fields=[NSMutableArray new];
for(NSArray* array in data)
{
[fields addObject: array[idx]];
}
[dict setObject: fields forKey: obj];
}];
In the case you haven't understood how it works, here is a further explanation:
This way at every execution of the block you can know which is the current object (obj) and it's index (idx). stop is just used to stop enumerating the array, but you don't need it in this case (say that you want to stop the enumeration, you set *stop=YES). In my code I just took every element at the index idx of data, and build an array which is the value that I put into the dictionary, that has obj (what you called key in your code) as key. For any further doubt feel free to ask any clarification through a comment.
The first thing to say is your code does not produce the desired output. You get an array with two dictionaries each with one key.
One way to solve the problem is like this:
NSMutableDictionary* mergedData = [[NSMutableDictionary alloc] init];
[keys enumerateObjectsUsingBlock: ^(id key, NSUInteger keyIndex, BOOL *stop)
{
NSMutableArray* keyValues = [[NSMutableArray alloc] init];
for (NSArray* row in data)
{
[keyValues addObject: [row objectAtIndex: keyIndex]];
}
[mergedData setObject: keyValues forKey: key];
}];
The above will throw an exception if a row doesn't have enough objects in it. You could either check it beforehand or allow the program to crash, it's up to you.
I have an NSArray containing n elements at indices 0, 1 ... n-1. I want to populate an NSDictionary with the contents of my array.
Specifically the dictionary should contain key-value pairs where the key is the hash of the ith element in the array and the value is the index into the array.
For example: array = [123, 101, 199] then the dictionary will contain three key-value pairs:
([123 hash], 0)
([199 hash], 2)
([101 hash], 1)
I've done this with a for loop over the array. What's a more concise way to do this? Perhaps something from NSKeyValueCoding?
More info: I'm thinking of something like this:
NSArray *keys = [myArray valueForKey:#"hash"];
NSArray *values = [myArray valueForKey:#"index"]; // #"index" needs to change
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:values
forKeys:keys];
I would probably use something like David's for loop solution myself, but just for kicks, and because I'm still trying to wrap my head completely around them, I came up with a solution using blocks:
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:[array count]];
[array enumerateObjectsUsingBlock:^ (id obj, NSUInteger idx, BOOL *stop) {
[dict setObject:[NSNumber numberWithUnsignedLong:idx] forKey:hashFor(obj)]; } ];
I'm assuming the existence of a function hashFor that generates the hash. You can replace that part with a message to obj or whatever you do to generate the hash.
A for loop is pretty good, especially if you need the index. Otherwise you might use fast enumeration:
int i = 0;
for (object in array) {
… [NSNumber numberWithInt: i] … // Add to dict
i++;
}
This has nothing to do with KVC.
I am trying to create an NSArray of bool values. How many I do this please?
NSArray *array = [[NSArray alloc] init];
array[0] = YES;
this does not work for me.
Thanks
NSArrays are not c-arrays. You cant access the values of an NSArray with array[foo];
But you can use c type arrays inside objective-C without problems.
The Objective-C approach would be:
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:[NSNumber numberWithBool:YES]];
//or
[array addObject:#(NO)];
...
BOOL b = [[array objectAtIndex:0] boolValue];
....
[array release];
EDIT: New versions of clang, the now standard compiler for objective-c, understand Object subscripting. When you use a new version of clang you will be able to use array[0] = #YES
Seems like you've confused c array with objc NSArray. NSArray is more like a list in Java, into which you can add objects, but not values like NSInteger, BOOL, double etc. If you wish to store such values in an NSArray, you first need to create a mutable array:
NSMutableArray* array = [[NSMutableArray alloc] init];
And then add proper object to it (in this case we'll use NSNumber to store your BOOL value):
[array addObject:[NSNumber numberWithBool:yourBoolValue]];
And that's pretty much it! If you wish to access the bool value, just call:
BOOL yourBoolValue = [[array objectAtIndex:0] boolValue];
Cheers,
Pawel
Use [NSNumber numberWithBool: YES] to get an object you can put in the collection.
How do I convert NSMutableArray to NSArray in objective-c?
NSArray *array = [mutableArray copy];
Copy makes immutable copies. This is quite useful because Apple can make various optimizations. For example sending copy to a immutable array only retains the object and returns self.
If you don't use garbage collection or ARC remember that -copy retains the object.
An NSMutableArray is a subclass of NSArray so you won't always need to convert but if you want to make sure that the array can't be modified you can create a NSArray either of these ways depending on whether you want it autoreleased or not:
/* Not autoreleased */
NSArray *array = [[NSArray alloc] initWithArray:mutableArray];
/* Autoreleased array */
NSArray *array = [NSArray arrayWithArray:mutableArray];
EDIT: The solution provided by Georg Schölly is a better way of doing it and a lot cleaner, especially now that we have ARC and don't even have to call autorelease.
I like both of the 2 main solutions:
NSArray *array = [NSArray arrayWithArray:mutableArray];
Or
NSArray *array = [mutableArray copy];
The primary difference I see in them is how they behave when mutableArray is nil:
NSMutableArray *mutableArray = nil;
NSArray *array = [NSArray arrayWithArray:mutableArray];
// array == #[] (empty array)
NSMutableArray *mutableArray = nil;
NSArray *array = [mutableArray copy];
// array == nil
you try this code---
NSMutableArray *myMutableArray = [myArray mutableCopy];
and
NSArray *myArray = [myMutableArray copy];
Objective-C
Below is way to convert NSMutableArray to NSArray:
//oldArray is having NSMutableArray data-type.
//Using Init with Array method.
NSArray *newArray1 = [[NSArray alloc]initWithArray:oldArray];
//Make copy of array
NSArray *newArray2 = [oldArray copy];
//Make mutablecopy of array
NSArray *newArray3 = [oldArray mutableCopy];
//Directly stored NSMutableArray to NSArray.
NSArray *newArray4 = oldArray;
Swift
In Swift 3.0 there is new data type Array. Declare Array using let keyword then it would become NSArray And if declare using var keyword then it's become NSMutableArray.
Sample code:
let newArray = oldArray as Array
In objective-c :
NSArray *myArray = [myMutableArray copy];
In swift :
var arr = myMutableArray as NSArray
NSArray *array = mutableArray;
This [mutableArray copy] antipattern is all over sample code. Stop doing so for throwaway mutable arrays that are transient and get deallocated at the end of the current scope.
There is no way the runtime could optimize out the wasteful copying of a mutable array that is just about to go out of scope, decrefed to 0 and deallocated for good.
If you're constructing an array via mutability and then want to return an immutable version, you can simply return the mutable array as an "NSArray" via inheritance.
- (NSArray *)arrayOfStrings {
NSMutableArray *mutableArray = [NSMutableArray array];
mutableArray[0] = #"foo";
mutableArray[1] = #"bar";
return mutableArray;
}
If you "trust" the caller to treat the (technically still mutable) return object as an immutable NSArray, this is a cheaper option than [mutableArray copy].
Apple concurs:
To determine whether it can change a received object, the receiver of a message must rely on the formal type of the return value. If it receives, for example, an array object typed as immutable, it should not attempt to mutate it. It is not an acceptable programming practice to determine if an object is mutable based on its class membership.
The above practice is discussed in more detail here:
Best Practice: Return mutableArray.copy or mutableArray if return type is NSArray
i was search for the answer in swift 3 and this question was showed as first result in search and i get inspired the answer from it
so here is the swift 3 code
let array: [String] = nsMutableArrayObject.copy() as! [String]