how can the whole NSMutableArray be filled with the same object(NSString) - objective-c

I'm trying this, but it looks like it's not right, are there any options? Thank you
NSMutableArray *copyy = [[NSMutableArray alloc] initWithCapacity:8];
for (int i = 1; i < copyy.count; i++) {
NSString *str = #"test";
[copyy addObject:[str copy][i]];
}

You can write a simple category on top of the NSArray like:
#interface NSArray(Repeating)
+ (NSArray*)arrayByRepeatingObject:(id)object times:(NSUInteger)t;
#end
#implementation NSArray(Repeating)
+ (NSArray*)arrayByRepeatingObject:(id)object times:(NSUInteger)t {
id objects[t];
for(NSUInteger i=0; i<t; ++i) objects[i] = object;
return [NSArray arrayWithObjects:objects count:t];
}
#end
so you can build an array by repeating an object like:
NSArray * items = [NSArray arrayByRepeatingObject:#"test" times:8];
Note: if you want a mutable version, just ask for a mutableCopy:
NSMutableArray * mutableItems = items.mutableCopy;

Related

how to add objects to existing array in objective c

I am new to objective c and having some problem with nsmutableArray.I have button and two textfields on my gui and i want that when i click on button the strings from textfields should be added to my existing array. But the problem is that when i click on button it always create new array.Help anybody.
my button code in myfile.m is as follows:
NSMutableArray* myArray = [NSMutableArray array];
NSString *strr=[textf stringValue];
NSString *strr1=[textf1 stringValue];
// [myArray addObject:strr]; // same with float values
// [myArray addObject:strr1];
[myArray addObject:strr];
[myArray addObject:strr1];
int i,j=0;
int count;
for (i = 0, count = [myArray count]; i < count; ){
NSString *element = [myArray objectAtIndex:i];
NSLog(#"The element at index %d in the array is: %#", i, element);
}
Because you always create new array in this line:
NSMutableArray* myArray = [NSMutableArray array];
Make your array as property of your class object. Example:
#interface MyClass ()
#property (nonatomic, strong) NSMutableArray * array;
#end
#implementation MyClass
- (id)init {
self = [super init];
if ( self ) {
_array = [NSMutableArray array];
}
return self;
}
- (IBAction)onButtonClick {
NSString *strr = [textf stringValue];
NSString *strr1 = [textf1 stringValue];
[self.array addObject:strr];
[self.array addObject:strr1];
for ( int i = 0; i < [myArray count]; i++ ) {
NSString * element = [myArray objectAtIndex:i];
NSLog(#"The element at index %d in the array is: %#", i, element);
}
}
#end

Printing a string object from an NSMutableArray

I stored some strings in objects and added the objects to an NSMutableArray. Now I want to print the strings in each element of the array. Clearly, I'm doing something wrong. I'm going to back and review these basics, but I was hoping someone could explain how I can print the string instead of the what looks to be the element address.
/** interface **/
#property (nonatomic, copy) NSString*myNumber;
-(void)setNumber: (NSString*) randomNumber;
/** implementation **/
#synthesize myNumber;
-(void) setNumber:(NSString *)randomNumber
{
myNumber = randomNumber;
}
/**main**/
Fraction * aFrac = [[Fraction alloc] init];
[aFrac setNumber:#"5/6"];
Fraction * bFrac = [[Fraction alloc] init];
[bFrac setNumber:#"2/3"];
NSMutableArray * myArray = [[NSMutableArray alloc] init];
[myArray addObject:aFrac];
[myArray addObject:bFrac];
int i;
for(i = 0; i<2; ++i)
{
id myArrayElement = [myArray objectAtIndex:i];
NSLog(#"%#", myArrayElement);
}
for(i = 0; i<2; ++i)
{
NSLog(#"%#", myArray[i]);
}
Both for loops print the same thing.
When you pass a custom object to NSLog you have to override the -(NSString)description method in that object.
So in your Fraction class if you simply override this function like so
- (NSString*)description
{
return self.myNumber;
}
that should log out what you want.
I would probably think about renaming that property from number as you are storing a string.
Hope that helps
I'm guessing the Fraction type you created has a NSString property or method named number (to match the -setNumber: method), in which case you would use the following code to print it:
NSLog("%#", [myArrayElement number]);
Or, for the second loop:
NSLog("%#", [myArray[i] number]);
In your code both for loop meaning has same only, try below
for(i = 0; i<2; ++i)
{
id myArrayElement = [myArray objectAtIndex:i];
NSLog(#"%#", myArrayElement.number);
}
for(i = 0; i<2; ++i)
{
NSLog(#"%#", myArray[i].number);
}
Now here two array value you are extracting
[myArray objectAtIndex:i] which is equivalent to myArray[i]

Self and arrays problems

I am new to Objective C and I'm having trouble getting my head around a few things.
I am trying to make a big integer program, from which I read items entered in a string and put them into an individual elements in the array.
I am currently working on an add method which adds elements from both the arrays together to make a big number stored in a final array.
But I'm kind of confused about to get this array I made from the initWithString method into the array method. I have some understanding of self, but I don't really know how to use it in this sense.
#implementation MPInteger
{
}
-(id) initWithString: (NSString *) x
{
self = [super init];
if (self) {
NSMutableArray *intString = [NSMutableArray array];
for (int i = 0; i < [x length]; i++) {
NSString *ch = [x substringWithRange:NSMakeRange(i, 1)];
[intString addObject:ch];
}
}
return self;
}
-(NSString *) description
{
return self.description;
}
-(MPInteger *) add: (MPInteger *) x
{
//NSMutableArray *arr1 = [NSMutableArray arrayWithCapacity:100];
//NSMutableArray *arr2 = [NSMutableArray arrayWithCapacity:100];
//for (int i=0; i < 100; i++) {
//int r = arc4random_uniform(1000);
//NSNumber *n = [NSNumber numberWithInteger:r];
//[arr1 addObject:n];
//[arr2 addObject:n];
// }
self.array = [NSMutableArray initialize];
return x;
}
#end
int main(int argc, const char * argv[]) {
#autoreleasepool {
MPInteger *x = [[MPInteger alloc] initWithString:#"123456789"];
MPInteger *y = [[MPInteger alloc] initWithString:#"123456789"];
[x add: y];
}
}
So I want too add the x and y arrays, but I'm not sure how to get the arrays in the add method. Do I use self to represent one of the arrays and initialise it, and x to represent the other. I don't know if I'm going about it completely the wrong way. Some help to understand would be greatly appreciated.
When referring to self you're actually accessing the current instance of the class. In other languages this may be implemented as this instead. There are a couple ways of designing the approach you're going for but the simplest pattern is probably composition:
#interface MPInteger
{
NSMutableArray *digits;
}
#end
----------------------------------------------------------------------------
#implementation MPInteger
-(id) initWithString: (NSString *) x
{
// Create a new instance of this class (MPInteger) with a default
// constructor and assign it to the current instance (self).
self = [super init];
if (self) {
// Previously we initialized a string, but then threw it out!
// Instead, let's save it to our string representation:
self->digits = [NSMutableArray array];
for (int i = 0; i < [x length]; i++) {
NSString *ch = [x substringWithRange:NSMakeRange(i, 1)];
[self->digits addObject:ch];
}
return self;
}
// Depending on how you want to implement this function, it could return
// a new MPInteger class or update the current instance (self):
-(MPInteger *) add: (MPInteger *) x
{
NSArray *a = self->digits;
NSArray *b = x->digits;
// Have both strings for A + B, so use them to find C:
NSArray *c = ????;
// Return a new instance of MPInteger with the result:
return [ [ MPInteger alloc ] initWithString:c ];
}
#end
Notice that now the MPInteger class has an instance of an NSString object that will exist during the entire lifetime of the MPInteger object. To update/access this string, all you need to do is say:
self->digits

How can I create array of numbers in Objective-C?

i trying to create my firsy iphone program and i realize that making an array or matrix of 2 dims is difficult for me... :-(
*how and where i declarer somthing like this (take from java) so all the function can see it:
int[] myArray = new int[6];
*how can i trnslete this function:
public int[] sortArray (int[] myArray){
int tmp;
for (int x = 0; x < myArray.length; x++) {
for (int y = x+1; y < 6; y++) {
if (myArray[y] < myArray[x]) {
tmp = myArray[x];
myArray[x] = myArray[y];
myArray[y] = tmp;
}
}
}
return myArray;
}
*and how i call this function?
sortArray(myArray);
thanks for everyone!!!
sharon
You can do it with one line of code:
NSArray *array = #[#[#1, #2, #3],
#[#4, #5, #6],
#[#7, #8, #9]];
Learn about Objective-C literals here.
As in C,
int twoDArray[3][3];
In objective-C
NSArray *a=#[#"apple",#"axe",#"ant"];
NSArray *b=#[#"ball",#"book",#"baby"];
NSArray *c=#[#"cup",#"cat",#"cow"];
NSArray *twoDArray=#[a,b,c];
or in one statement:
NSArray *twoDArray=#[#[#"apple",#"axe",#"ant"],
#[#"ball",#"book",#"baby"],
#[#"cup",#"cat",#"cow"]];
EDIT:
NO need to convert that java function to obj-c method.
To sort the array :
NSArray *sortedArray = [array sortedArrayUsingComparator:^(id str1, id str2) {
return [((NSString *)str1) compare:((NSString *)str2) options:NSNumericSearch];
}];
EDIT 2: (Removed unwanted typecast of nsstring to id and back to string)
NSArray *sortedArray = [array sortedArrayUsingComparator:^(NSString *str1, NSString *str2) {
return [str1 compare:str2 options:NSNumericSearch];
}];
Declare in your respective .h file
NSMutableArray *numbers;
Then in your .m file
numbers = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < 6; i++)
[numbers addObject:[NSNumber numberWithInteger:i]];
and declare it in your .h as
-(NSMutableArray *)sortArray:(NSMutableArray *)numbers;
This is the translated method above in Objective-C:
-(NSMutableArray *)sortArray:(NSMutableArray *)numbers
{
NSInteger tmp = 0;
for(int x = 0; x < [numbers count]; x++)
for(int y = x + 1; y < 6; y++)
if([numbers objectAtIndex:y] < [numbers objectAtIndex:x])
{
tmp = [numbers objectAtIndex:x];
[numbers replaceObjectAtIndex:x withObject:[numbers objectAtIndex:y]];
[numbers replaceObjectAtIndex:y withObject:tmp];
}
return numbers;
}
Also you can call a method in objective-c as follows:
[self sortArray:numbers];
You seem to have (at least) two related-but separate questions here.
1/ how to create an array of numbers
Objective-C arrays come as immutable NSArrays (fixed contents) or mutable NSMutableArrays (you can add delete and shuffle contents around). You sort function as written is asking for a mutable array.
To create and populate an immutable array with NSNumber objects:
NSArray* array = #[#3,#5,#8,#2,#9,#1]; //"#1" is an NSNumber object literal
//access: array[3] etc
Multidimensional:
NSArray* arrayOfArrays #[#[#3,#5,#8],#[#2,#9,#1]];
//access: arrayOfArrays[1][2] etc
To create an empty variable-length mutable array
NSMutableArray* mutableArray = [[NSMutableArray alloc] init];
Create and populate a variable-length mutable array
myArray = [NSMutableArray arrayWithObjects:#3,#5,#8,#2,#9,#1, nil]; //note nil termination
To turn your immutable NSArray into a mutable NSMutableArray
NSMutableArray* mutableArray = [array mutableCopy];
(but take care, this will only render the top level as mutable, if it contains immutable subarrays they will remain immutable)
Objective-C collections (NSArray, NSDictionary, NSSet) can only hold objective-C objects. Therefore if you want to store ints or floats you need to box them into objective-C NSNumber objects before adding to a collection, and unbox them again to access the value.
int x;
float y;
NSNumber xNum = [NSNumber numberWithInt:x]; //box
NSNumber yNum = [NSNumber numberWithFloat:y]; //box
x = [xNum intValue]; //unbox
y = [yNum floatValue]; //unbox
2/ how to translate code
Here is a like-for-like translation:
To create the (mutable) myArray object:
NSMutableArray* myArray = [[NSMutableArray alloc] init];
Populate it:
[myArray addObjects:#3,#6,#8,#1,#9,nil]; //last value is nil to indicate termination
The method:
- sortArray:(NSMutableArray*)myArray
{
id tmp;
for (int x = 0; x < [myArray count]; x++) {
for (int y = x+1; y < 6; y++) {
if ([myArray[y] floatValue] < [myArray[x] floatValue]) {
tmp = myArray[x];
myArray[x] = myArray[y];
myArray[y] = tmp;
}
}
}
}
To call:
[self sortArray:myArray];
To declare with object scope, make a property in your #interface section
#interface myObject:NSObject
#property (nonatomic, strong) NSMutableArray* myArray;
#end
You will still need to create myArray before you can use it:
self.myArray = [[NSMutableArray alloc] init];
but you will be able to set and access it's values from anywhere inside the object thus:
self.myArray
And - if it is in the public header file #interface section - from outside the object thus:
myObject.myArray

how to get different array on different index of single array

i have one array named invoiceInfo1 & i pass it to another array named allInfo.
But I want for different index of invoiceInfo ,the different array is created & pass it to allInfo.
Mycode is as follow:
for (int i=0; i<[userdata count]; i++) {
NSLog(#" userdata count :%d",[userdata count]);
invoiceInfo1 = [NSMutableArray arrayWithObjects:[[userdata objectAtIndex:i]valueForKey:#"fname"], [[userdata
objectAtIndex:i]valueForKey:#"name"],
[[userdata objectAtIndex:i]valueForKey:#"address"],
[[userdata objectAtIndex:i]valueForKey:#"city"], nil];
NSLog(#" info1 is:%#",invoiceInfo1); // invoiceInfo get overwrite when loop execute
NSMutableArray* allInfo = [NSMutableArray arrayWithObjects:headers,invoiceInfo1 , nil];
// HERE I Want Generate New Array of different index of invoiceInfo1 & pass it to allInfo
}
Create a NSObject class with header and info array:
#interface AllInfo: NSObject
{
NSMutableArray *header;
NSMutableArray *info;
}
#property (nonatomic, retain) NSMutableArray *header;
#property (nonatomic, retain) NSMutableArray *info;
#end
#implementation AllInfo
#synthesize header;
#synthesize info;
#end
Then implement this code:
allInfo = [[NSMutableArray alloc] init];
for (int i=0; i<[userdata count]; i++) {
NSLog(#" userdata count :%d",[userdata count]);
NSMutableArray *invoiceInfo1 = [[NSMutableArray alloc] init];
[invoiceInfo1 addObject:[userdata objectAtIndex:i]valueForKey:#"fname"]];
[invoiceInfo1 addObject:[userdata objectAtIndex:i]valueForKey:#"name"]];
[invoiceInfo1 addObject:[userdata objectAtIndex:i]valueForKey:#"address"]];
[invoiceInfo1 addObject:[userdata objectAtIndex:i]valueForKey:#"city"]];
NSLog(#" info1 is:%#",invoiceInfo1); // invoiceInfo get overwrite when loop execute
AllInfo *newInfo = [[AllInfo alloc] init];
newInfo.header = headers;
newInfo.info = invoiceInfo1;
[allInfo addObject:newInfo];
// HERE I Want Generate New Array of different index of invoiceInfo1 & pass it to allInfo
}
Hope this will help.