Create a dynamic array - objective-c

I am new. It's a basic question i guess.
Suppose I need to have a dynamic array to store several objects from my Own class,like classA. I ve no idea about how to wrap these classA-objects and put 'em into the array, maybe NSMutableArray. thx alot.
#interface classA
{
int x;
int y;
}
...
classA *a,*b,*c;

Initialize your array with :
NSMutableArray *myArray = [[NSMutableArray alloc] init];
And then add an object with :
[myArray addObject:a];
[myArray addObject:b];
And so on
You can find it all explained here : https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html

If you need your array to be mutable,
NSMutableArray *arr = [NSMutableArray arrayWithCapacity:2];
[arr addObject:a];
[arr addObject:b];
will suffice. Objective-C, like Smalltalk, uses dynamic typing. You can just add the objects.
If you do not need to mutate your array,
NSArray *arr = #[a, b];

Related

creating an array of NSObject classes

I have a NSObject class in which I am sending a NSDictionary object too, the class object then sets all the entries in the NSDictionary to their native types that are variables in the NSObject class.
I would then like to pass this NSObject class into its own NSMutableArray however my app is crashing when this happens.
below is the code calling the NSObject Class and then trying to set it into a NSMutableArray.
NSArray *filteredArray = parsedDataArrayOfDictionaries; //dictionary entries are currently in nsstring format
SearchResultList *searchResultList = [[SearchResultList alloc]init];
NSMutableArray *testArray = [[NSMutableArray alloc] init];
int myCount = 0;
while (myCount <= [filteredArray count]) {
//call class and pass current NSDictionary in array[myCount]
[searchResultList assignSearchData:filteredArray[myCount]];
searchResultList = (SearchResultList*)[testingDic objectForKey:#"myObject"];
testArray[myCount] = searchResultList; //create array of nsobjectclassed, this is also where the app fails
NSLog(#"%#", testArray[myCount]);
}
Hopefully this is making some sense, I am getting abit lost in the middle of the while statements... I know I need to get back the NSObject Class then assign it to an array.. but im just not sure how to do this, any help would be greatly appreciated.
You are exceeding the size of the array filteredArray
while (myCount <= [filteredArray count]) {
should read
while (myCount <[filteredArray count]) {
as the count of an array is one higher than the last object's index, as the indices starts at 0.
honestly I am not sure, what you are trying to achieve, but you should consider to use fast enumeration instead of the while statement
for (id obj in filteredArray) {
or even fancier block-based enumeration
NSMutableArray *testArray = [[NSMutableArray alloc] init];
[filteredArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//...
[testArray addObject:obj];
}];
Try using NSMutableArray addObject. There is no 'C' style [] operator for NSMutableArray.

Arrays of NSObjects in Objective-C

I've created an object, and now I'm trying to create an array full of these objects. I've tried a few different things with no success.
How can I do this?
You can do it one of two ways, with NSArray or NSMutableArray.
id obj1, obj2, obj3;
// This creates a static array
NSArray *array = [NSArray arrayWithObjects: obj1, obj2, obj3, nil];
// This creates a dynamic array
NSMutableArray *mutarray = [NSMutableArray array];
[mutarray addObject:obj1];
[mutarray addObject:obj2];
[mutarray addObject:obj3];
NSMutableArray * arrayOfFoos = [NSMutableArray array];
for (int i = 0; i < 100; ++i) {
Foo * f = [[Foo alloc] init];
[arrayOfFoos addObject:f];
[f release];
}
You can use an NSArray, take a look at Apple's documentation.
If you wanna add them incrementally consider using a mutable collection like an NSMutableArray (here in the doc)

NSArray filled with bool

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 add data from NSMutableString into NSArray?

is it an possible to add a value from an NSMutableString into an NSArray? Whats the snippet?
Actually, Mike is wrong. If you want to instantiate an NSArray with a single NSMutableString object, you can do the following:
NSMutableString *myString; //Assuming your string is here
NSArray *array = [NSArray arrayWithObject:myString];
There is no arrayWithElements in NSArray (see NSArray documentation)
If you want to instantiate an NSArray with a single NSMutableString object, you can do the following:
NSString *myString; //Assuming your string is here
NSArray *array = [NSArray arrayWithObjects:myString,nil];
Note that NSArray will be immutable - that is, you can't add or remove objects to it after you've made it. If you want the array to be mutable, you'll have to create an NSMutableArray. To use an NSMutableArray in this fashion, you can do the following:
NSString *myString; //Assuming your string is here
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:myString];
NSArray is immutable, so you cannot add values to it. You should use NSMutableArray in order to do that with the addObject: method.
NSMutableString *str = ...
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:str];
// You must use NSMutableArray to add Object to array
NSMutableArray *tableCellNames;
// arrayWithCapacity is a required parameter to define limit of your object.
tableCellNames = [NSMutableArray arrayWithCapacity:total_rows];
[tableCellNames addObject:title];
NSLog(#"Array table cell %#",tableCellNames);
//Thanks VKJ
An elegant solution would be this:
NSMutableString *str; //your string here
NSArray *newArray = #[str];
Using the new notation, it's a piece of cake.

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]