Incrementing NSArray on button click - iphone

I'm reading a text file line by line, and storing it into a NSArray.
What I want to achieve is to increment the index of my NSArray when the user clicks a button.
Code:
text.editable = NO;
NSString *fileString = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]pathForResource:#"firstyea" ofType:#"txt"] encoding:NSUTF8StringEncoding error:nil]; // reads file into memory as an NSString
NSArray *lines = [fileString componentsSeparatedByString:#"\n"]; // each line, adjust character for line endings
NSString *wat = [lines objectAtIndex:1];
text.text = wat;
[self.view addSubview:text];
So I have to increment objectAtIndex by 1 whenever the user clicks a button.
I can do it in C++ by having a variable of type int, and saying something like objectAtIndex:counter++ but I don't know how to do the same thing in IOS.

You can't do it with NSArray, you need to use a NSMutableArray
You should take a variable of type static int.
For example:
static int counter=0; //define it globally
NSMutableArray *tempArray=[[NSMutableArray alloc] init];
[tempArray insertObject:#"Your Data From File" atIndex:counter++];
Note: Don't forget to release the array after you're finished using it!

Declare an integer i globally. #property int i;
in
viewDidLoad
, declare i=0;
-(IBAction)BtnClick:(id)sender
{
if ( i < lines.count )
{
NSString *wat = [lines objectAtIndex:i];
i=i+1;
}
}
Hope this helps.

Related

Unable to create NSMutableArray using for-loop

i want to have an array with values "25 kg", "26 kg"... "149 kg", "150 kg". To simplify task i wrote this:
-(NSMutableArray*)weightArray{
NSMutableArray *myArray;
for (int i=25; i++; i<150){
NSString *weightString;
weightString = [NSString stringWithFormat:#"%d kg", i];
[myArray addObject:weightString];
}
return myArray;
}
And then in viewDidload in my view i wrote: NSLog (#"%#", [self weightArray]);
But it looks like it's not working. I might be missing something obvious like syntax. Why is it not working?
UPDATE:
Finally i found a solution - first, i declare weightArray in #implementation section, then i wrote:
-(void)fillingArray{
if (!weightArray){
for (int i=25; i<150 ;i++){
NSString *weightString = [[NSMutableArray alloc] init];
weightString = [NSString stringWithFormat:#"%d kg", i];
[weightArray addObject:weightString];
NSLog(#"%#", weightString);
}
}
}
In viewDidLoad i wrote:
[self fillingArray];
NSLog(#"%#", weightArray);
I think, my problem was in that string NSLog(#"%#", [self weightArray]); In square brackets it suppose to be method name, but i was trying to point at array, and nothing happening.
There are 3 problems with what you are doing.
You need to create your array like this: NSMutableArray *myArray = [[NSMutableArray alloc] init]; so that it will actually exist.
Your NSLog needs to be NSLog (#"%#", [self weightArray]); since you are lgging an array and not a number.
(thanks rmaddy for pointing this out) The 2nd and 3rd part of your for statement are reversed. So, i++ is your condition and is always non-zero. This infinite loop is what causes your machine to lock up.
EDIT: Here's a better way that only creates the array once.
-(NSMutableArray*)weightArray{
static NSMutableArray *myArray;
if (!myArray){
myArray = [[NSMutableArray alloc] init];
for (int i=25; i<150 ;i++){
NSString *weightString;
weightString = [NSString stringWithFormat:#"%d kg", i];
[myArray addObject:weightString];
}
}
return myArray;
}
You don't allocate and initialize the array. So it has an indeterminate value, and your program invokes undefined beahvior. Create it actually:
NSMutableArray *myArray = [NSMutableArray new];

How to create image and labels using location data stored in NSArray

i have to create an 2images and 3 labels by using code (cgrectmake)and i am having X location, y location, width and height all are stored in arrays(which i have retrieved from the web services)how can i create the image and labels can any one help me
You can join the elements of an array together with the NSString componentsJoinedByString class method:
NSString myString = [myNSArray componentsJoinedByString:#"x"];
where x is the characters you'd like to appear between each array element.
Edited to add
So in your newly-added code if these are the label values:
lbl = #"zero"
lbl1 = #"one"
lbl2 = #"two"
and you want to join them together with a space character then if you did this:
NSString *temp = [labelArray componentsJoinedByString:#" "];
NSLog(#"temp = %#", temp);
then this is what would be logged:
zero one two
Edited to further add
If you are instead trying to join the label values together to make xml elements then you might do something like this:
NSString *joinedElements = [labelArray componentsJoinedByString:#"</label><label>"];
NSString *temp = [NSString stringWithFormat:#"<label>%#</label>", joinedElements];
NSLog(#"temp = %#", temp);
then this is what would be logged:
<label>zero</label><label>one</label><label>two</label>
may be this is usefull to you.
NSString *str;
str = [arrayName objectAtIndex:i(Index NO)];
OK by this easily you can access object from the array. any type of object u can fetch this way only reception object type are change in left side.
Best of Luck.
Most objects have a -description method which returns a string representation of the object:
- (NSString *)description;
For example:
NSArray *array = [NSArray arrayWithObjects:#"The", #"quick", #"brown", #"fox", nil];
NSLog(#"%#", array); // prints the contents of the array out to the console.
NSString *arrayDescription = [array description]; // a string
It would help to know what you want to do with the string (how will you use the string). Also, what kind of objects do you have in the array?
In that case, Matthew's answer is one possibility. Another might be to use an NSMutableString and append the individual items, if you need control over how the string is created:
NSMutableString *string = [NSMutableString string];
if ([array count] >= 3) {
[string appendString:[array objectAtIndex:0]];
[string appendFormat:#"blah some filler text %#", [array objectAtIndex:1]];
[string appendString:[array objectAtIndex:2]];
}

Convert char to int to NSString

I am writing some code to allow users to answer multiple choice questions. So I have an NSArray of values [#"value1", #"value2", ..]
I want to display them as:
A) value1
B) value2
The code I have is
for(int i = i; i < [values count]; i = i+1) {
NSString *displayValue = [[NSString alloc] initWithString:<NEED HELP HERE>];
displayValue = [displayValue stringByAppendingString:#") "];
displayValue = [displayValue stringByAppendingString:[values objectAtIndex:i];
}
The question I have is if there is where I have put , how could I convert i to the right ASCII character (A, B, C, etc) and initialize the string with that value
NSString *displayValue = [NSString stringWithFormat:#"%c",'A'-1+i];
and to get the whole string at once, use:
NSString *displayValue = [NSString stringWithFormat:#"%c) %#",'A'-1+i,
[values objectAtIndex:i]];
(ps. if you alloc an object, you must also release or autorelease, or you will "leak" memory)
Look at NSString:initWithFormat method, along with the String Programming Guide.

How to include a C array in -description

I'm trying to include the elements of an array in the NSString that's returned by the -description method in my class. No clue how to do this in Objective-C...in Java there's string concatenation or StringBuilder, what's the equivalent in Obj-C?
TIA..
Just use NSArray's componentsJoinedByString: method with whatever you want between them as the argument.
NSString *elementsSquishedTogether = [myArray componentsJoinedByString:#""];
NSString *connectedByACommaAndSpace = [myArray componentsJoinedByString:#", "];
If you have a C array, you can turn it into an NSArray with NSArray *converted = [NSArray arrayWithObjects:yourCArray count:yourArrayCount].
The title of your thread talks about C arrays, so here's a modification of jsumners' answer that will deal wiith C arrays.
myArray is assumed to be an ivar declared thusly:
int* myArray;
storage for myArray is assumed to be malloc'd at some point and the size of it is in an ivar declared:
int myArraySize;
The code for description goes something like
- (NSString *)description
{
NSMutableString *returnString = [[[NSMutableString alloc] init] autorelease];
for (int i = 0 ; i < myArraySize ; i++)
{
if (i > 0)
{
[returnString appendString: #", "];
}
[returnString appendFormat: #"%d", myArray[i]];
}
return [NSString stringWithFormat: #"[%#]", returnString];
}
There are variations. The above version formats the string with bracket delimiters and commas between elements. Also, it returns an NSString instead of an NSMutableString which is not a big deal, but I feel that if you say you are returning an immutable object, you probably should.
The following could should "build" a string representation of your array. Notice that it is using the -description method of the objects in the array. If you want something different you will have to make the necessary change.
- (NSString *)description: (id) myArr {
NSMutableString *returnString = [[[NSMutableString alloc] init] autorelease];
for (int i = 0, j = [myaArr count]; i < j; i++) {
[returnString appendString: [[myArr objectAtIndex: i] description]];
}
return [NSString stringWithString: returnString];
}
Edit:
As JeremyP said, I answered this using Objective-C arrays. I guess I just forgot the question when I started writing my code. I'm going to leave my answer as an alternative way to do it, though. I've also fixed the return string type from a mutable string to an immutable string (as it should be).

NSArray to NSMutableArray as random stack

Just a conceptual description first:
I am reading input from a text file (a list of words) and putting these words into an NSArray using componentsSeparatedByString method. This works.
But I wanted to select the words randomly and then delete them from the array so as to ensure a different word each time. Of course, you cannot change the NSArray contents. So...
I copied the contents of the NSArray into an NSMutableArray and use IT for the selection source. This also works - 269 objects in each array.
To return a word from the NSMutableArray I use the following code:
note- the arrays are declared globally
as
arrMutTextWords = [[NSMutableArray alloc] init]; //stack for words
arrTextWords = [[NSArray alloc] init]; //permanent store for words
-(NSString*) getaTextWord
{
// if the mutable text word array is empty refill
if ([arrMutTextWords count] == 0){
for (int i = 0 ; i < [arrTextWords count]; i++)
[arrMutTextWords addObject:[arrTextWords objectAtIndex:i]];
}
int i = random() % [arrMutTextWords count];
NSString* ptrWord = [arrMutTextWords objectAtIndex:i];
[arrMutTextWords removeObjectAtIndex:i];
return ptrWord;
}
The program crashes during a call to the method above - here is the calling code:
arrTmp is declared globally arrTmp = [[NSArray alloc] init]; //tmp store for words
for (int i = 0 ; i < 4; i++) {
tmpWord = [self getaTextWord];
[arrTmp addObject:tmpWord];
[arrTmp addObject:tmpWord];
}
I'm thinking that somehow deleting strings from arrMutTextWords is invalidating the NSArray - but I can't think how this would occur.
One possible source for problems is your fetching AND removing the NSString object from your list. Removing it releases that NSString instance therefore devalidating your reference.
To be shure to retain a reference you should use this code sequence instead:
NSString * ptrWord = [[[arrMutTextWords objectAtIndex:i] retain] autorelease];
[arrMutTextWords removeObjectAtIndex:i];
return ptrWord;
By the way: You should use
NSMutableArray *mutableArray = [NSMutableArray arrayWithArray: array];
instead of copying all values by hand. While i do not know the implementation of NSMutableArray, i know from times long ago (NeXTstep), that there are several possible optimizations that may speed up basic NSArray operations.
And finally copying this way is much more concise.
Just ran this through XCode and got random words returned, however I skipped the whole for loop and used addObjectsFromArrayfrom NSMutableArray.
NSArray *randomArray = [[NSArray alloc] initWithObjects:#"Paul", #"George", #"John", nil];
NSMutableArray *muteArray = [[NSMutableArray alloc] init];
[muteArray addObjectsFromArray:randomArray];
int i = random() % [muteArray count];
NSString* ptrWord = [muteArray objectAtIndex:i];
[muteArray removeObjectAtIndex:i];
NSLog(#"ptrWord %#", ptrWord); //gave me a different name each time I ran the function.
Hope this clears some things up.