create array of single ivar from array objects with multiple ivars - objective-c

if i have an class with two properties "a" and "b" and i have an array of these class instances. What is the best way to create an array of only only "a" elements.

The simplest way is Key-Value Coding:
[yourArray valueForKey:#"a"];

Just iterate over the class instances and build your new array:
// Presuming some NSArray * classInstances of type MyClass
NSMutableArray * aProperties = [[[NSMutableArray alloc]
initWithCapacity:[classInstances count]]
autorelease];
for(MyClass * myInstance in classInstances) {
[aProperties addObject:[myInstance a]];
}
If your class is key-value coding compliant for a, you can also ask the array for the values directly:
NSArray * aProperties = [classInstances valueForKey:#"a"];

Related

How to add new array element from another method in Objective-c?

I have some array( #private NSArray employees []; ) and method , which take string parameter( name of employees) and put this parameter in array. How I can do this with Objective-c?
You could do the following,
Create a property,
#property (nonatomic) NSMutableArray *array;
Initialise the array in your init method or somewhere else appropriate,
self.array = [[NSMutableArray alloc] init];
Your method could look something like this,
- (void)addEmployeeName:(NSString *)employeeName {
[self.array addObject:employeeName];
}
You can create a class Employee and use a type with your array.
For example:
NSArray<Employee*> * employees = [[NSArray alloc] init];
At this point, your method will be:
-(Employee *)createEmployee:(NSString *)name{
Employee *myEmpl = [[Employee alloc]init];
[myEmpl setName:name];
return myEmpl;
}
and you can add the object (of type Employee) in your array in this way:
[employees addObject:[self createEmployee]];
the same thing is possibile with an object of type NSString instead of Employee.
You can also avoid defining the type in your NSArray because Objective-C use the type inference

Objective C Array of Array of Strings

I'm trying to make an array of array of strings so that I can eventually pull out something like ArrayOfArrays[0][1] = "hi".
NSString *ArrayOne[] = {#"hello", #"hi"};
NSString *ArrayTwo[] = {#"goodbye", #"bye"};
NSArray *ArrayOfArrays[] = {#[*ArrayOne, *ArrayTwo]};
However when I try to do this, I get an error: Initializer element is not a compile-time constant.
I've read that this is because I'm creating an array with dynamic values, though it should be static. Not sure how to work around this.
Any advice on making an array of array of strings?
Use NSArray, or rather NSMutableArray if you want to modify it after creation:
NSMutableArray *arrayOne = [#[#"hello", #"hi"] mutableCopy];
NSMutableArray *arrayTwo = [#[#"goodbye", #"bye"] mutableCopy];
NSMutableArray *arrayOfArrays = [#[arrayOne, arrayTwo] mutableCopy];
There are other ways to initialise it, but this is the only way that allows you to use Objective-C literal syntax.
You cannot store plain ol' C arrays within an Objective-C collection class as your code attempts to do.
You wrote:
it should be static
if this is what you want then your use of C arrays is quite valid, you just got the syntax wrong. You can use:
NSString *arrayOfArrays[][2] =
{ {#"hello", #"hi"},
{#"goodbye", #"bye"},
};
Important: The 2 is the number of elements in the inner array, you do not change it when adding further pairs.
This will give you a compile-time static array.
If what you are making is a map from one word to another you might be better off with a dictionary, e.g.:
NSDictionary *wordMap =
#{ #"hello" : #"hi",
#"goodbye" : #"bye"
};
and accessing an element becomes:
wordMap[#"hello"];
Note: the dictionary "constant" here is actually executed code; the C array version can appear as a global or local initialiser, while the dictionary initialisation must be done in a method/function - but it can assign to a global.
HTH
NSArray *array = #[
#[[ #"hello", #"hi" ] mutableCopy],
#[[ #"goodbye", #"bye" ] mutableCopy],
];
NSLog(#"%# is short for %#", array[0][1], array[0][0]);
Output: hi is short for hello

Object Class Array Casting for a Method in Objective C

I have an object Student with 4 attributes(age,name,department,surname).
and I create an array of that object like this;
Student students[10] blah blah init blah.
then i want to use an Student array as argument for a method;
-(void) displayStudentInArray : (????) studentarray atIndex: (int) index {.....}
'???' are my problem. what do i write there? i ve no idea.
need help. i m new on objective c.
Rather than using C notation the array should be made like this:
NSArray *studentArray = [[NSArray alloc] initWithObjects: student1, student2, student2, ..., nil];
In which case the parameter type will be NSArray
-(void) displayStudentInArray : (NSArray *)studentarray atIndex: (int) index {.....}
The preferred method for creating arrays is using NSArray (or NSMutableArray if you want to modify the array after it is created):
NSArray *array = [[NSArray alloc]initWithObjects:student1, student2...];
Then your method signature would be:
-(void)displayStudentInArray:(NSArray *)studentarray atIndex:(int)index
These answers are correct, but if you really want to use C notation, you just need to add another asterisk to denote a reference to another pointer:
- (void)displayStudentInArray:(Student**)studentArray atIndex:(int)index {
Student* firstStudent = studentArray[1];
//do what you want with the array
}
This is because C arrays are really just pointers to an address in memory. If you wanted a C array for a primitive, it would look like this:
int* arrayOfInts = malloc(yourSize * sizeof(int));
You have an array of objects, but the idea is just the same. You just add one more asterisk to denote that it's a pointer to a pointer to an object.
Student** students = ...
Just write
Student *tempStudent = (array)[0];

object array to NSMutable array [duplicate]

This question already has an answer here:
Getting an array of a property from an object array
(1 answer)
Closed 7 years ago.
I have an array of Objects.Object contains three values, id,name,value.I want to parse name from this object array and want to create a different array of names only....Can anyone help Plz.....
int i;
NSInteger *namesCount=[eCategories count]; //eCategories is an object array
SubCategories *subCategoriesList=[[SubCategories alloc] init];
//SubCategories is a NSObject class containing cat_name,cat_id,cat_value.
NSMutableArray *nameArray=[[NSMutableArray alloc]init];
for(i=0;i<namesCount;i++)
{
subCategoriesList=[eCategories objectAtIndex:i];
nameArray=subCategoriesList.cat_name;
}
NSArray has a method -valueForKey: which does exactly what you want in one message
Returns an array containing the results of invoking valueForKey: using key on each of the array's objects.
NSArray* nameArray = [eCategories valueForKey: #"cat_name"];
How about
[objects valueForKeyPath: #"#distinctUnionOfArrays.name"]
Unless, of course, the objects inside the array are not NSDictionaries with "name" as the key for the names. You're not telling us enough.
int i;
NSInteger *namesCount=[eCategories count]; //eCategories is an object array
SubCategories *subCategoriesList=[[SubCategories alloc] init];
//SubCategories is a NSObject class containing cat_name,cat_id,cat_value.
NSMutableArray *nameArray=[[NSMutableArray alloc]init];
for(i=0;i
[nameArray addobject:subCategoriesList.cat_name];
}

How to declare class array in objective c

I can declare NSMutableArray or NSArray but I want to declare class array. Let say user is a class so I can declare array as:
user* obj[10];
it is valid in Objective c, but I am not sure how I can set array capacity dynamically. Which we usually do with MutableArray as initWithCapacity:..
This is what I am doing with class:
user* objuser;
CustomOutput* output = [[CustomOutput alloc] init];
[objuser cutomSerialize:output];
NSMutableData* data = output.data;
But If I have array as:
NSMutableArray* aryUserObj;
I can't call cutomSerialize method from arryUserObj.
I want to Serialize all the userObj at ones and get a single NSData object.
The standard approach to serialize an array of objects is for you to define encodeWithCoder: and initWithCoder: in your User object:
#interface User: NSObject {
....
}
-(void)encodeWithCoder:(NSCoder*)coder ;
-(id)initWithCoder:(NSCoder*)coder;
#end
What you currently have in CustomSerialize should be in these methods.
Then, if you want to encode an object, you do
User* user=... ;
NSData* data=[NSKeyedArchiver archivedDataWithRootObject:user];
and decode it:
User* user=[NSKeyedUnarchiver unarchiveObjectWithData:data];
If you have an array of objects,
NSMutableArray* array=... ; // an array of users
NSData* data=[NSKeyedArchiver archivedDataWithRootObject:array];
and
NSArray* array=[NSKeyedUnarchiver unarchiveObjectWithData:data];
Iteration over array is done automatically.
Note also that you don't get the mutable array back, it's an immutable array.
NSMutableArray * users = [NSMutableArray array];
for (int i = 0; i < someNumber; ++i) {
User * aUser = [[User alloc] initWithStuff:someStuff];
[users addObject:aUser];
[aUser release];
}