NSArray filled with bool - objective-c

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.

Related

Multidimensional Arrays in Objective C

I have an NSDictionary filled with data. If this was php it might be accessed by  something like:
$data = $array['all_items'][0]['name'];
How do I do something similar in objective c? ($array would be an NSDictionary)
The equivalent code in Objective-C is:
id data = [[[array objectForKey:#"all_items"] objectAtIndex:0] objectForKey:#"name"];
Note that objectForKey: is a method of NSDictionary, and objectAtIndex: is a method of NSArray.
A shortcut in Xcode 4.5, using LLVM 4.1, is:
id data = array[#"all_items"][0][#"name"];
Also note that if "array" is an NSDictionary instance and you want to get an array of all values in the dictionary, you use the allValues method of NSDictionary:
id data = [array allValues][0][#"name"];
Of course, allValues returns an unsorted array, so accessing the array by index is not very useful. More typically, you'd see:
for (NSDictionary* value in [array allValues])
{
id data = value[#"name"];
// do something with data
}
Unfortunately the objective-c version is not as elegant syntactically as the PHP version:
NSDictionary *array = ...;
NSArray *foo = [array objectForKey#"all_items"];
NSDictionary *bar = [foo objectAtIndex:0];
NSString *data = [bar objectForKey#"name"];
For brevity, you can do this on a single line as:
NSString *data = [[[array objectForKey#"all_items"] objectAtIndex:0] objectForKey#"name"];
You should use it,
NSString *value = [[multiArray objectAtIndex:1] objectAtIndex:0];
You can look the question here

How to put in array a different types of field in objective-c

I'm writing an app for iPhone in objective-c. I want to declare an array that will hold different type of fields , like: int, NSString, bool.
Can I do it?
You can put whatever items in an NSArray as long as they are objects. So you have to wrap items that are not objects (such as BOOL, int and CGPoint) in some kind of objects such as NSNumber or NSValue.
NSMutableArray *array = [[NSMutableArray] alloc] init];
[array addObject:myString];
[array addObject:[NSNumber numberWithInt:1]];
[array addObject:[NSNumber numberWithFloat:1.0]];
[array addObject:[NSValue valueWithPoint:myPoint]]; // myPoint is a CGPoint
[array addObject:[NSValue valueWithRect:myRect]]; // myRect is a CGRect
Yes, you can
NSMutableArray *array = [NSMutableArray array];
NSString *string = #"str";
[array addObject:string]; //string
NSNumber *num = [NSNumber numberWithInt:1];
[array addObject:num]; //int
NSNumber *boolNum = [NSNumber numberWithBool:YES];
[array addObject:boolNum]; //bool
Use NSMutableArray.
NSMutableArray *array = [[NSMutableArray alloc]init];
Now use addObject: method to add objects. for adding int, bool value create NSNumber object.
It is possible. Just create the array and add the objects you want added.

Add NSStrings to mutable array

I created a mutable array and I have two NSString variables. Now I want to add these two NSStrings to my array. How is this possible? Thanks.
Use the addObject function of you NSMutableArray.
eg.
[myNSMutableArray addObject:myString1];
[myNSMutableArray addObject:myString2];
Jhaliya's answer is correct. +1 vote.
I added a immutable version so you can see the difference. If you dont want to remove or add more objects (NSStrings) to your container, I would recommend using an Immutable version.
Mutable version:
NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
NSString *string_one = #"One"];
[mutableArray addObject:string_one];
//Or
[mutableArray addObject:#"Two"];
NSLog(#"%#", mutableArray);
Immutable version
NSArray *immutableArray = [NSArray arrayWithObjects:#"One", #"Two", nil];
NSLog(#"%#", immutableArray);
You can add at NSMutableArray allocation.
Like :
NSMutableArray *test = [NSMutableArray arrayWithObjects:#"test1",#"test2",nil];

How to deal with booleans in NSMutableArrays?

Can someone tell me why my application crashes here ?
and why it does not crash when i replace the YES objects with NSString values ?
all i want to do is to store boolean data into array and to modify these data later,
can someone please tell me how to do this ?
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableArray* arr = [[NSMutableArray alloc] initWithObjects:YES, YES, YES, YES, nil];
NSLog([arr objectAtIndex:1]);
}
YES and NO are BOOLs, which is not an Objective-C class. Foundation containers can only store Objective-C objects.
You need to wrap them in an NSNumber, like:
NSNumber* yesObj = [NSNumber numberWithBool:YES];
NSMutableArray* arr = [[NSMutableArray alloc] initWithObjects:
yesObj, yesObj, yesObj, yesObj, nil];
NSLog(#"%d", [[arr objectAtIndex:1] boolValue]);
The reason why it accepts NSString is because an NSString is a kind of Objective-C class.

How do I convert NSMutableArray to NSArray?

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]