print reverse of a string - iphone

I am writing a program which prints the reverse of a string in a textfield, taking input text from the other textfield. When I press enter after entering text into one textfield the result(reverse) should be dispalyed in the other text field.
I have tried like this, but am getting weird results.
.h file:
#import <UIKit/UIKit.h>
#interface reverseVC : UIViewController {
UITextField *textEntered;
UITextField *textDisplay;
}
#property (nonatomic,retain) IBOutlet UITextField *textDisplay;
#property (nonatomic,retain) IBOutlet UITextField *textEntered;
- (NSMutableArray*) stringReverse;
- (IBAction) enter;
#end
.m file
- (NSMutableArray *) stringReverse
{
NSString *value = textEntered.text;
NSArray *tempArray = [[[NSArray alloc] initWithObjects:value,nil] autorelease];
NSMutableArray *arr = [[[NSMutableArray alloc] init] autorelease];
for (int i=[tempArray count]-1; i>=0; i--)
{
[arr addObject:[tempArray objectAtIndex:i]];
NSLog(#"the object is:%c",arr);
}
return arr;
}
-(IBAction)enter
{
textDisplay.text = [NSString stringWithFormat:#"%c",[self stringReverse]];
}
Earlier got warnings like SIG_ABT and EXE_BAD_ACCESS before placing nil and autorelease in array initialisations. Now the warnings are solved but results undesiredly.
Where am I going wrong?

You insert the NSString object in your array. Its count is 1. You have to go from the end of the string to the beginning and append the character to a new string. You ca do it like this:
-(NSString*)reverseString:(NSString*)string {
NSMutableString *reversedString;
int length = [string length];
reversedString = [NSMutableString stringWithCapacity:length];
while (length--) {
[reversedString appendFormat:#"%C", [string characterAtIndex:length]];
}
return reversedString;
}

Another way to reverse strings is to use the reverse string enumerator.
- (NSString *)reverseString:(NSString *)string {
NSMutableString *reversedString = [[NSMutableString alloc] init];
NSRange fullRange = [string rangeOfString:string];
NSStringEnumerationOptions enumerationOptions = (NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences);
[string enumerateSubstringsInRange:fullRange options:enumerationOptions usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[reversedString appendString:substring];
}];
return reversedString;
}

use this
NSString *str=textEntered.text;//
NSMutableArray *temp=[[NSMutableArray alloc] init];
for(int i=0;i<[str length];i++)
{
[temp addObject:[NSString stringWithFormat:#"%c",[str characterAtIndex:i]]];
}
temp = [NSMutableArray arrayWithArray:[[temp reverseObjectEnumerator] allObjects]];
NSString *reverseString=#"";
for(int i=0;i<[temp count];i++)
{
reverseString=[NSString stringWithFormat:#"%#%#",reverseString,[temp objectAtIndex:i]];
}
NSLog(#"%#",reverseString);

I revers my strings with a few lines of code. Rather late, but just putting it out there :)
- (NSString*) reverseMyString:(NSString*)theString
{
NSString *final = #"";
for(int i = theString.length-1; i>=0; i--)
final = [NSString stringWithFormat:#"%#%c", final, [theString characterAtIndex:i]];
return final;
}

NSString *str = #"hello";
int length = [str length];
NSLog(#"%d",length);
NSMutableString *rev = [[NSMutableString alloc] initWithCapacity:[str length]];
while (length > 0) {
--length;
[rev appendString:[NSString stringWithFormat:#"%c", [str characterAtIndex:length]]];
}
NSLog(#"%#", rev);

Using characterAtIndex doesn't work well with non-ascii characters.
- (NSString *)reverseMyString:(NSString *)string {
NSString *output = [[NSString alloc] init];
for(int i = string.length-1; i>=0; i--) {
output = [output stringByAppendingString:[string substringWithRange:NSMakeRange(i, 1)]];
}
return output;
}

Related

Reverse strings in array objectivec [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reverse NSString text
i am new on objectovec. i have a array having strings. how to reverse each string?
which method of NSArray and NSstring will help me out?
i want reversed string in the array.
thanks
Create a method that will return a reversed string.
-(NSString *)reverseString:(NSString *)string{
NSString *reverseString=[NSString new];
for (NSInteger i=string.length-1; i>-1; i--) {
reverseString=[reverseString stringByAppendingFormat:#"%c",[string characterAtIndex:i]];
}
return reverseString;
}
In your any of the method :
NSMutableArray *names=[NSMutableArray arrayWithObjects:#"anoop",#"johnson",#"wasim",nil];
for (NSInteger i=0; i<names.count; i++) {
names[i]=[self reverseString:names[i]];
}
NSLog(#"%#",names);
Hope this help
NSString *str=textEntered.text;//
NSMutableArray *temp=[[NSMutableArray alloc] init];
for(int i=0;i<[str length];i++)
{
[temp addObject:[NSString stringWithFormat:#"%c",[str characterAtIndex:i]]];
}
temp = [NSMutableArray arrayWithArray:[[temp reverseObjectEnumerator] allObjects]];
NSString *reverseString=#"";
for(int i=0;i<[temp count];i++)
{
reverseString=[NSString stringWithFormat:#"%#%#",reverseString,[temp objectAtIndex:i]];
}
NSLog(#"%#",reverseString);
NSString *str=textEntered.text;//
NSMutableArray *temp=[[NSMutableArray alloc] init];
for(int i=0;i<[str length];i++)
{
[temp addObject:[NSString stringWithFormat:#"%c",[str characterAtIndex:i]]];
}
temp = [NSMutableArray arrayWithArray:[[temp reverseObjectEnumerator] allObjects]];
NSString *reverseString=#"";
for(int i=0;i<[temp count];i++)
{
reverseString=[NSString stringWithFormat:#"%#%#",reverseString,[temp objectAtIndex:i]];
}
NSLog(#"%#",reverseString);
AnOther way for revers string NSStringEnumerationOptions
- (NSString *)reverseString:(NSString *)string {
NSMutableString *reversedString = [[NSMutableString alloc] init];
NSRange fullRange = [string rangeOfString:string];
NSStringEnumerationOptions enumerationOptions = (NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences);
[string enumerateSubstringsInRange:fullRange options:enumerationOptions usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[reversedString appendString:substring];
}];
return reversedString;
}
Use
unichar c[yourstring.Length];
NSRange raneg={0,yourstring.Length};
[yourstring getCharacters:c range:raneg];
//c will be an array of your string do what ever you wish
Use this one to reverse your string and then store back to your array at same index.
-(NSString*)reverseString:(NSString*)string {
NSMutableString *reversedString;
int length = [string length];
reversedString = [NSMutableString stringWithCapacity:length];
while (length--) {
[reversedString appendFormat:#"%c", [string characterAtIndex:length]];
}
return reversedString;
}
But if you have mutable string then you can create a category
#interface NSMutableString (Reverse)
- (void)reverseString;
#end
#implementation NSMutableString (Reverse)
- (void)reverseString {
for (int i = 0; i < self.length/2; i++) {
int l = self.length - 1 - i;
NSRange iRange = NSMakeRange(i, 1);
NSRange lRange = NSMakeRange(l, 1);
NSString *iStr = [self substringWithRange:iRange];
NSString *lStr = [self substringWithRange:lRange];
[self replaceCharactersInRange:iRange withString:lStr];
[self replaceCharactersInRange:lRange withString:iStr];
}
}
#end
And then you can use this category method like this
NSArray *arr = [NSArray arrayWithObjects:[#"hello" mutableCopy], [#"Do it now" mutableCopy], [#"Test string, 123 123" mutableCopy], nil];
NSLog(#"%#",arr);
[arr makeObjectsPerformSelector:#selector(reverseString)];
NSLog(#"%#",arr);

Display NSMutableArray in UIlabel in xcode

I have to display NSmutableArray data in UIlabel .But only the last index text is getting added .Here is my code
marray:
(
{
ID=1;
}
{
ID="2"
}
)
for(int i=0;i<[marray count];i++)
{
eventName=[[arr2 objectAtIndex:i]objectForKey:#"Code"];
label.text=[NSString stringWithFormat:#"ID :%#",eventName ];
}
I have to display these ID's in UIlabel with text as : 1 , 2
How can I do it?
you can append string to NSString object than use that object in label like bellow
NSMutableString *lblstr=#"ID :";
for (int i=0; i<[marray count]; i++) {
eventName=[[arr2 objectAtIndex:i]objectForKey:#"Code"];
[lblstr appendString:[NSString stringWithFormat:#"%#",eventName ]];
}
label.text=lblstr;
You are running a for loop which will continue executing till its last increment . So the last value in the array would be displayed. So what you can do is that you can add a timer instead of a for loop that is if you want to show your NSmutableArray as changing in the UILabel.
EDIT:
-(IBAction) rotate3
{
NSString *number = [self.dayArray description];
NSArray *array = [[NSArray alloc] initWithObjects: #"0", #"1", #"2", #"3", #"4", #"5" ,#"6", #"7", #"8",#"9",#"10",#"11",#"12",#"13", #"14", #"15", #"16", #"17", #"18", #"19",nil];
numberCount++;
timer=[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:#selector(rotate3 )userInfo:nil repeats:YES];
self.dayArray = array;
[array release];
label.text = [NSString stringWithFormat:#"Day %# ", number];
}
Also check these links How to update UILabel programmatically in iOS and How to display an NSArray in a UILabel and use timer
Try the below Code.
NSString *temp=#"";
for(int i=0;i<[marray count];i++)
{
//eventName=[[arr2 objectAtIndex:i]objectForKey:#"Code"];
temp=[temp stringByAppendingString:[[arr2 objectAtIndex:i]objectForKey:#"Code"]];
temp=[temp stringByAppendingString:#" ,"];
}
temp = [temp substringToIndex:[temp length]-1];
label.text=[NSString stringWithFormat:#"ID :%#",temp ];
NSMutableString *str = [[NSMutableString alloc] init];
for(int i=0;i<[marray count];i++)
{
NSString *temp = [NSString stringWithFormat:#"%d - %#\n",i+1, [[arr2 objectAtIndex:i]objectForKey:#"Code"]];
[str appendString:[NSString stringWithFormat:#"%#",temp]];
//sleep(0.05); //Remove comment this line may help ! **Tricky Line**
}
label.text = str;
[str release];
You may create an array of objects (indexes) and use componentsJoinedByString:
NSString* str = [array componentsJoindeByString: #", "];
Or using your code, replacing
label.text=[NSString stringWithFormat:#"ID :%#",eventName ];
with:
label.text=[label.text stringByAppendingFormat:#", %#", eventName];

Memory leak in NSMutableArray, NSArray, NSString in iPhone SDK

In my app, I got Memory leaks in NSMutableArray, NSArray and NSString.
Here is the code.
NSString *subQuery = [NSString stringWithFormat:#"SELECT %# FROM tbl_lang WHERE glossary = '%#'",append1,glossaryName];
NSArray *subArray1 = [[[self returnExecuteQuery:subQuery] mutableCopy] autorelease];
[subArray addObjectsFromArray:subArray1];
NSString *columnQuery = [NSString stringWithFormat:#"select AutoID,%# from tbl_lang where glossary='%#'",lblshortName.text,glossaryName];
NSArray *newArray =[[[self returnExecuteQuery:columnQuery] mutableCopy] autorelease];
[langArray addObjectsFromArray:newArray];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
for (int i=0; i<[newArray count]; i++) {
NSString *cellText = [[newArray objectAtIndex:i] valueForKey:[NSString stringWithFormat:#"%#",lblshortName.text]];
if (cellText != (NSString *)[NSNull null] && ![cellText isEqualToString:#""] ) {
NSString *decodedString3 = [NSString stringWithUTF8String:[cellText cStringUsingEncoding:[NSString defaultCStringEncoding]]];
[tempArray addObject:[NSString stringWithFormat:#"%# : %#",lblshortName.text, decodedString3]];
}
else {
[tempArray addObject:#"<empty>"];
}
NSString *detail = #"_________________";
for (int j=0; j<[lableNameArray count]; j++) {
NSString *checkNull=[[subArray1 objectAtIndex:i] valueForKey:[NSString stringWithFormat:#"%#",[lableNameArray objectAtIndex:j]]];
if(checkNull != (NSString *)[NSNull null] && checkNull.length > 0)
{
NSString *decodedString4 = [NSString stringWithUTF8String:[checkNull cStringUsingEncoding:[NSString defaultCStringEncoding]]];
detail = [NSString stringWithFormat:#"%#\n%# : %# ",detail,[lableNameArray objectAtIndex:j],decodedString4];
}
}
[detailTextArray addObject:detail];
}
When I run in Instruments I got leaks in
-subArray1 in second line.
-detail (NSString) in second for loop.
And subArray and langArray are my global arrays.
If I remove mutableCopy from NSArray *newArray =[[[self returnExecuteQuery:columnQuery] mutableCopy] autorelease]; and NSArray *subArray1 = [[[self returnExecuteQuery:subQuery] mutableCopy] autorelease]; then subArray and langArray doesnot retain values.
How to avoid memory leak in this code?
Olease try this one, in above code you are creating two many objects that belong to autorelease pool here is one version where I tried to handle release of those string variables.
Second this is that the leak of detail is because you are de-referencing it many times in your code. And for subArray1 please see the comment
NSMutableString *subQuery =[ [NSMutableString alloc] initWithFormat:#"SELECT %# FROM tbl_lang WHERE glossary = '%#'",append1,glossaryName];
// please make returnExecuteQuery's returned array autorelease if it is not.
NSArray *subArray1 = [[self returnExecuteQuery:subQuery] mutableCopy] ;
[subArray addObjectsFromArray:subArray1];
[subQuery release];
NSMutableString *columnQuery ==[ [NSMutableString alloc] initWithFormat:#"select AutoID,%# from tbl_lang where glossary='%#'",lblshortName.text,glossaryName];
NSArray *newArray =[[self returnExecuteQuery:columnQuery] mutableCopy] ;
[langArray addObjectsFromArray:newArray];
[columnQuery relese];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
for (int i=0; i<[newArray count]; i++) {
NSMutableString *tempKey = [[NSMutableString alloc]initWithFormat:#"%#",lblshortName.text]];
NSString *cellText = [[newArray objectAtIndex:i] valueForKey:tempKey];
[tempKey release];
if (cellText != (NSString *)[NSNull null] && ![cellText isEqualToString:#""] ) {
NSString *decodedString3 = [NSString stringWithUTF8String:[cellText cStringUsingEncoding:[NSString defaultCStringEncoding]]];
NSMutableString *tempString = [[NSMutableString alloc] initWithFormat:#"%# : %#",lblshortName.text, decodedString3]];
[tempArray addObject:tempString];
[tempString release];
}
else {
[tempArray addObject:#"<empty>"];
}
NSMutableString *detail = nil;
for (int j=0; j<[lableNameArray count]; j++)
{
detail = [[ NSMutableString alloc]initWithString:#"_________________"];
NSMutableString *key = [[NSMutableString alloc]initWithFormat:#"%#",[lableNameArray objectAtIndex:j]];
NSString *checkNull=[[subArray1 objectAtIndex:i] valueForKey:key];
[key release];
if(checkNull != (NSString *)[NSNull null] && checkNull.length > 0)
{
NSString *decodedString4 = [NSString stringWithUTF8String:[checkNull cStringUsingEncoding:[NSString defaultCStringEncoding]]];
[detail setString:[NSString stringWithFormat:#"%#\n%# : %# ",detail,[lableNameArray objectAtIndex:j],decodedString4]];
}
[detailTextArray addObject:detail];
[detail release];
}
}
[subArray1 release];
[newArray release];
UPDATE : Please do read comments in the code and reply back so that things could be improved.
NSMutableString *subQuery =[ [NSMutableString alloc] initWithFormat:#"SELECT %# FROM tbl_lang WHERE glossary = '%#'",append1,glossaryName];
//*****NOTE THIS POINT ----> please make returnExecuteQuery's returned array autorelease if it is not.
NSArray *subArray1 = [[self returnExecuteQuery:subQuery] mutableCopy] ;
[subArray addObjectsFromArray:subArray1];
[subQuery release];
NSMutableString *columnQuery ==[ [NSMutableString alloc] initWithFormat:#"select AutoID,%# from tbl_lang where glossary='%#'",lblshortName.text,glossaryName];
//*****NOTE THIS POINT ----> please make returnExecuteQuery's returned array autorelease if it is not.
NSArray *newArray =[[self returnExecuteQuery:columnQuery] mutableCopy] ;
[langArray addObjectsFromArray:newArray];
[columnQuery relese];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
for (int i=0; i<[newArray count]; i++) {
NSMutableString *tempKey = [[NSMutableString alloc]initWithFormat:#"%#",lblshortName.text]];
NSString *cellText = [[newArray objectAtIndex:i] valueForKey:tempKey];
[tempKey release];
if (cellText != (NSString *)[NSNull null] && ![cellText isEqualToString:#""] ) {
NSString *decodedString3 = [NSString stringWithUTF8String:[cellText cStringUsingEncoding:[NSString defaultCStringEncoding]]];
NSMutableString *tempString = [[NSMutableString alloc] initWithFormat:#"%# : %#",lblshortName.text, decodedString3]];
[tempArray addObject:tempString];
[tempString release];
}
else {
[tempArray addObject:#"<empty>"];
}
NSMutableString *detail = [[ NSMutableString alloc]initWithString:#"_________________"];
for (int j=0; j<[lableNameArray count]; j++)
{
NSMutableString *key = [[NSMutableString alloc]initWithFormat:#"%#",[lableNameArray objectAtIndex:j]];
NSString *checkNull=[[subArray1 objectAtIndex:i] valueForKey:key]; //also here if you note you are using subArray1 not subArray?
[key release];
if(checkNull != (NSString *)[NSNull null] && checkNull.length > 0)
{
NSString *decodedString4 = [NSString stringWithUTF8String:[checkNull cStringUsingEncoding:[NSString defaultCStringEncoding]]];
[detail setString:[NSString stringWithFormat:#"%#\n%# : %# ",detail,[lableNameArray objectAtIndex:j],decodedString4]];
break;//I am not sure why you are checking this condition but assume that you want to get NOT NULL VALUE and add it to array?
}
}
[detailTextArray addObject:detail];
[detail release];
}
[subArray1 release];
[newArray release];
UPDATE 2:
if(checkNull != (NSString *)[NSNull null] && checkNull.length > 0)
{
NSString *decodedString4 = [NSString stringWithUTF8String:[checkNull cStringUsingEncoding:[NSString defaultCStringEncoding]]];
[detail appendFormat:#"%#\n%# : %# ",detail,[lableNameArray objectAtIndex:j],decodedString4]];
}
Thanks,
Not sure what is causing the memory leak, but this may help. This is a more direct way of copying the arrays, and may result in avoiding the leak:
NSArray *langArray =[[NSArray alloc] initWithArray: [self returnExecuteQuery:columnQuery] copyItems: YES];
This basically makes a one-level deep copy of the array returned by returnExecuteQuery. You can read about it in more detail in Collections Programming Topics.
I'm not sure how mutableCopy works and that may have something to do with the leak. If it copies the objects in the old array & then adds them to the new array, they may enter the array with a retain count of 2 (1 from the copy, and 1 from being added to an array.) It doesn't make much sense that it should work this way. But, if it does, that could account for the leak.
You could start by releasing your tempArray once done with it (after the loops).
Often, the higher levels leaks are hidden in the flood of lower level ones (ie a container leaking causes all its content to be leaked as well), which might be the case for your string.
Using mutableCopy] autorelease]; is fine by the way.

How can I retrieve an object from NSDictionary to set up table

I guys,
I am fighting with a problem since some days and wanted to get your assistance.
I have an RSS file on a server which gets parsed normally. Basically it's about shows, concerts, gigs of a band. That's why I have created the Show-Class:
Show.h:
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#interface Show : NSObject {
NSString* gigName;
NSString* date;
NSString* place;
NSString* door;
NSString* time;
NSString* bands;
NSString* entry;
NSString* query;
NSString* flyer;
NSString* type;
}
- (id)init:(NSString*)gigName date:(NSString*)date place:(NSString*)place door:(NSString*)door time:(NSString*)time bands:(NSString*)bands
entry:(NSString*)entry query:(NSString*)query flyer:(NSString*)flyer type:(NSString*)type;
#property (nonatomic, retain) NSString* gigName;
#property (nonatomic, retain) NSString* date;
#property (nonatomic, retain) NSString* place;
#property (nonatomic, retain) NSString* door;
#property (nonatomic, retain) NSString* time;
#property (nonatomic, retain) NSString* bands;
#property (nonatomic, retain) NSString* entry;
#property (nonatomic, retain) NSString* query;
#property (nonatomic, retain) NSString* flyer;
#property (nonatomic, retain) NSString* type;
#end
and the Show.m:
#import "Show.h"
#implementation Show
#synthesize gigName, date , place, door, time, bands, entry, query, flyer, type;
- (id)init:(NSString*)_gigName date:(NSString*)_date place:(NSString*)_place door:(NSString*)_door time:(NSString*)_time bands:(NSString*)_bands
entry:(NSString*)_entry query:(NSString*)_query flyer:(NSString*)_flyer type:(NSString*)_type {
//if (self = [super init]) {
self = [super init];
if(self) {
gigName = _gigName;
date = _date;
place = _place;
door = _door;
time = _time;
bands = _bands;
entry = _entry;
query = _query;
flyer = _flyer;
type = _type;
}
return self;
}
- (void)dealloc {
[super dealloc];
}
#end
In my TourViewController (which is a table view) i have created this:
- (void)viewDidLoad {
[super viewDidLoad];
//Initialize the array.
listOfItems = [[NSMutableArray alloc] init];
pastShowArray = [NSMutableArray arrayWithCapacity:[stories count]]; // needs to be mutable
futureShowArray = [NSMutableArray arrayWithCapacity:[stories count]]; // needs to be mutable
for(int i = 0; i < [stories count]; i++) {
// get fields from story parser object
gigName = [[stories objectAtIndex:i] objectForKey:#"gig"];
type = [[stories objectAtIndex:i] objectForKey:#"type"];
date = [[stories objectAtIndex:i] objectForKey:#"date"];
place = [[stories objectAtIndex:i] objectForKey:#"place"];
door = [[stories objectAtIndex:i] objectForKey:#"door"];
time = [[stories objectAtIndex:i] objectForKey:#"time"];
bands = [[stories objectAtIndex:i] objectForKey:#"bands"];
entry = [[stories objectAtIndex:i] objectForKey:#"entry"];
query = [[stories objectAtIndex:i] objectForKey:#"query"];
flyer = [[stories objectAtIndex:i] objectForKey:#"flyer"];
// remove unnecessary whitespaces
gigName = [gigName stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
type = [type stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
date = [date stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
place = [place stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
door = [door stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
time = [time stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
bands = [bands stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
entry = [entry stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
query = [query stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
flyer = [flyer stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(gigName);
NSLog(type);
Show* show = [[Show alloc] init:gigName date:date place:place door:door time:time bands:bands entry:entry query:query flyer:flyer type:type];
if([type isEqualToString:#"past"]) {
// fill past show array
NSLog(#"adding past object now");
[pastShowArray addObject:show];
} else {
// fill future show array
NSLog(#"adding future object now");
[futureShowArray addObject:show];
}
}
NSMutableDictionary *pastShowsArrayDict = [NSMutableDictionary dictionaryWithObject:pastShowArray forKey:#"Show"];
NSLog(#"added past show array to pastshowarraydict");
NSMutableDictionary *futureShowsArrayDict = [NSMutableDictionary dictionaryWithObject:futureShowArray forKey:#"Show"];
NSLog(#"added future show array to futureshowarraydict");
[listOfItems addObject:pastShowsArrayDict];
[listOfItems addObject:futureShowsArrayDict];
//Set the title
self.navigationItem.title = #"Tour";
}
As far as I can tell, that worked all without problems. Now I want to show the "gigName" of the show in the table. For this I need to get the show object from the NSDictionary. I have this but it crashes:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
// Set up the cell...
NSLog(#"try to set up cell");
//First get the dictionary object
NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:#"Show"];
Show *show = [array objectAtIndex:indexPath.row];
NSLog(show.gigName);
cell.text = show.gigName;
return cell;
}
Error Output:
2011-02-14 16:32:44.462 All in Vain [405:307] try to set up cell
terminate called after throwing an instance of 'NSException'
Program received signal: “SIGABRT”.
Can you guys tell me how I can get the show object and set the table text to show.gigName?
Any help is appreaciated. Thank you,
cheers,
doonot
In your init:... for the Show object you need to make it:
self.gigName = _gigName;
self.date = _date;
self.place = _place;
self.door = _door;
self.time = _time;
self.bands = _bands;
self.entry = _entry;
self.query = _query;
self.flyer = _flyer;
self.type = _type;
so that each of them are retained (or do gigName = [_gigName retain]; but then you loose the release if it was not empty).
You may also have the same problem in the view controller and the way the variables are being set there but without seeing more I can't be sure.
Try to change this :
cell.text = show.gigName;
into :
cell.textLabel.text = show.gigName;

iPhone SDK: loading UITableView from SQLite - creating array from SQLite

this is a follow up forr iPhone SDK: loading UITableView from SQLite
I am planning to use following code to load SQL data to the array. Each element of the array will be a class represening each database entry:
#interface Row : NSObject {
int PK;
NSString *desc;
}
#property int PK;
#property (nonatomic, retain) NSString *desc;
#end
the loading operation will be similar to this:
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:1];
Row *myRow = [[Row alloc] init];
for (int i=0; i<10; i++)
{
myRow.PK = i;
myRow.desc = [[NSString alloc] initWithFormat:#"Hello: %d", i];
[array addObject:myRow];
}
[myRow release];
for (int i=0; i < [array count]; i++)
{
Row *myNrow = [array objectAtIndex:i] ;
NSLog (#"%# %d", [myNrow desc], [myNrow PK]);
myNrow = nil;
}
Of course first for loop will be a loop from SELECT statement. The other loop (or elements of that loop) will be in the cellInRowIndex method to render data.
I have a question about memory leaks. Does the code above have memory leaks? The decs string property of the Row class is declared as (retain). SHould not it be released somewhere?
Thanks
You should release the string that you're putting into myRow.desc. You could change
myRow.desc = [[NSString alloc] initWithFormat:#"Hello: %d", i];
to either
myRow.desc = [[[NSString alloc] initWithFormat:#"Hello: %d", i] autorelease];
or
myRow.desc = [NSString stringWithFormat:#"Hello: %d", i];
EDIT: If you want to use an intermediate NSString (as you mentioned in the comment), you could either do it like this:
NSString *foo = [[NSString alloc] initWithFormat:#"Hello: %d", i];
myRow.desc = foo;
[foo release];
or:
NSString *foo = [NSString stringWithFormat:#"Hello: %d", i];
myRow.desc = foo;
Note that in the second example foo is already autoreleased, so you mustn't release it.