Releasing static object - iphone

I know in vast of the cases I don't have to release static variable. However the following is the code for my model:
+ (UIImage*)imageForTag
{
static UIImage *imgTag;
if(imgTag == nil)
{
NSString* imageName = [[NSBundle mainBundle]
pathForResource:#"tag" ofType:#"png"];
imgTag = [[[UIImage alloc]
initWithContentsOfFile:imageName] autorelease];
}
return imgTag;
}
and here is my data table part
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
}
if (indexPath.row == 0)
{
cell.imageView.image = [DataModel imageForSmtng];
}
else if(indexPath.row == 1)
{
cell.imageView.image = [DataModel imageForTag];
}
return cell;
This will crash on cell.imageView.image = [DataModel imageForTag] second time due to imageForTag is pointing to invalid address. If I add retain on that it will not crash. Is it wrong to remove autorelease from above and forget about imgTag references?

It is wrong. Because when you call autorelease on the imgTag variable, you just released the object it points to. But, the imgTag variable still points to that range of memory. So, when you call the imgTag again, it is not nil, it still points to something, an invalid thing.
So, the solution should be either:
1/ You shouldn't release it at all
2/ You have to release it manually when you think that it is a good time to release it. And then remember to do: imgTag = nil

Related

Populating UITableView with NSArray in iOS 7

A lot of the methods have deprecated in iOS 7 in order to set font, textLabel, and color for UITableView cells. I'm also just having a difficult time populating the view with these values. Here's a snippet of my code:
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSArray* jobs = [json objectForKey:#"results"];
for(NSDictionary *jobsInfo in jobs) {
JobInfo *jobby = [[JobInfo alloc] init];
jobby.city = jobsInfo[#"city"];
jobby.company = jobsInfo[#"company"];
jobby.url = jobsInfo[#"url"];
jobby.title = jobsInfo[#"jobtitle"];
jobby.snippet = jobsInfo[#"snippet"];
jobby.state = jobsInfo[#"state"];
jobby.time = jobsInfo[#"date"];
jobsArray = [jobsInfo objectForKey:#"results"];
}
}
I am looping through an array of dictionaries from a GET request and parsed. I am now attempting to fill my UITableView with the following code:
-
(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [jobsArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *jobsDic = [jobsArray objectAtIndex:indexPath.row];
[cell.textLabel setText:[jobsDic objectForKey:#"jobtitle"]];
return cell;
}
Also, I have declared this is in my .h file:
NSArray *jobsDic;
Any ideas on what I'm doing wrong? Is this an iOS 7 problem?
It seems that you reinitialize jobsarray at the end of the forin loop.
You didn't mean ?
NSArray* jobs = [json objectForKey:#"results"];
NSMutableArray *jobsTemp = [[NSMutableArray alloc] initWithCapacity:jobs.count];
for(NSDictionary *jobsInfo in jobs) {
JobInfo *jobby = [[JobInfo alloc] init];
jobby.city = jobsInfo[#"city"];
jobby.company = jobsInfo[#"company"];
jobby.url = jobsInfo[#"url"];
jobby.title = jobsInfo[#"jobtitle"];
jobby.snippet = jobsInfo[#"snippet"];
jobby.state = jobsInfo[#"state"];
jobby.time = jobsInfo[#"date"];
[jobsTemp addObject:jobby];
}
self.jobsArray = jobsTemp; //set #property (nonatomic, copy) NSArray *jobsArray; in the .h
[self.tableView reloadData]; //optional only if the data is loaded after the view
In the cell for row method :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
JobInfo *job = self.jobsArray[indexPath.row];
cell.textLabel.text = job.title;
return cell;
}
And don't forget :
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.jobsArray.count;
}
Update - an user suggested an edit :
It's true that count isn't a NSArray property. But as Objective-C lets us use a shortcut notation for calling method with a dot, this code works. You have to know limitation of this : if you use a NSArray subclass with a count property with a custom getter this could have side effects #property (nonatomic, strong, getter=myCustomCount) NSUInteger count. As I think code readability is to me one of most important things I prefer to use dot notation. I think Apple SHOULD implement count as readonly property so I use it this way (but it's my point of view). So for those which don't agree with me just read return [self.jobsArray count]; in the tableView:numberOfRowsInSection: method.
Change the declaration of jobsArray from NSArray to NSMutableArray.
Add an initialization at the beginning point of fetchedData method like follows.
if(!jobsArray) {
jobsArray = [NSMutableArray array];
}
else {
[jobsArray removeAllObjects];
}
Remove the following line.
jobsArray = [jobsInfo objectForKey:#"results"];
Instead of that, add the initialized object to the array at the end of for loop.
[jobsArray addObject:jobby];
Add a [tableView reloadData]; at the end of your *-(void)fetchedData:(NSData )responseData; method implementation.
Initially when you are loading the view, tableView will get populated. After you received the data, tableView will not be known that it is received.
Everything else seems good. Hope rest will work fine.

How to Show UITableViewCellAccessoryCheckmark

I have a tableview which has a list of options the user has selcected( It is an edit page ).
the tableview looks as below
Apple UITableViewCellAccessoryCheckmark
Orange UITableViewCellAccessoryNone
Pineapple UITableViewCellAccessoryCheckmark Banana
UITableViewCellAccessoryNone
- (void)viewDidLoad {
self.mySavedFruitsArray = [myDBOperations getMyFruitsList:[appDelegate getDBPath]:self.myId];
}
/ Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
//-------------------------------------------------------------------------------
{
static NSString *CellIdentifier = #"PoemTypeCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:#"MyIdentifier"]autorelease];
}
NSDictionary *aDict = [self.myFruitsArr objectAtIndex:indexPath.row];
NSString *aValue = [aDict objectForKey:#"value"];
NSString *aId = [aDict objectForKey:#"key"];
cell.textLabel.text = aValue;
cell.accessoryType = UITableViewCellAccessoryNone;
NSDictionary *aSavedDict = [self.mySavedFruitsArray objectAtIndex:indexPath.row];
NSString *Value = [aSavedDict objectForKey:#"value"];
NSString *Id = [aSavedDict objectForKey:#"key"];
if ( aId == Id ){
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
mySavedFruitsArray - it holds the user selected fruits.
myFruitsArr - this has common list of fruits
now i would like to know how to display UITableViewCellAccessoryCheckmark for cell which matches with mySavedFruitsArray.
I mean , in this edit view i want to display the fruits list with user selected option.
Pls let me know how to do that.
I tried like this, but no use.
/ Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
//-------------------------------------------------------------------------------
{
static NSString *CellIdentifier = #"PoemTypeCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:#"MyIdentifier"]autorelease];
}
NSDictionary *aDict = [self.myFruitsArr objectAtIndex:indexPath.row];
NSString *aValue = [aDict objectForKey:#"value"];
NSString *aId = [aDict objectForKey:#"key"];
cell.textLabel.text = aValue;
cell.accessoryType = UITableViewCellAccessoryNone;
NSDictionary *aSavedDict = [self.mySavedFruitsArray objectAtIndex:indexPath.row];
NSString *Value = [aSavedDict objectForKey:#"value"];
NSString *Id = [aSavedDict objectForKey:#"key"];
if ( aId == Id ){
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
pls note self.mySavedFruitsArray may not be equal to myFruitsArr always ( because user may select only one fruit).
if ( aId == Id ){
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
string comparison is wrong. You should compare strings this way:
if([aId isEqualToString:Id]) {
....
}
instead of checking if ( aId == Id ) which compares the strings as identical objects,
use if ([aID isEqualToString:Id]) which compares strings
In a version downloaded yesterday (6/8/14), UITableViewCellAccessoryCheckmark and UITableViewCellAccessoryNone is not valid. It was throwing compiler errors for me. I think you are supposed to use it as an enum, like so:
if item.completed {
cell!.accessoryType = UITableViewCellAccessoryType.Checkmark
} else {
cell!.accessoryType = UITableViewCellAccessoryType.None
}
With this change, my code compiles and the behavior appears in the simulator.
Sorry I don't know which version to look up (UIKit?), I'm new to iOS development.

How to print the array value in cells lable?

I am developing a application in that I want to print the array value in the cell contain label place. I got the vlaues for array like names=[results valueForKey:#"name"].
I write the code for print that value in a lable in cellForRowAtIndexPath like
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
NSInteger row=indexPath.row;
cell = [self getCellContentView:CellIdentifier];
UILabel *lblTemp1 = (UILabel *)[cell viewWithTag:1];
lblTemp1.text = [names objectAtIndex:row];
//lblTemp2.text = [names objectAtIndex:row];
return cell;
}
but ,when the application got the error at lblTemp1.text = [names objectAtIndex:row] like Program received signal: “EXC_BAD_ACCESS”.So please tell me how to solve this problem.
It seems you've missed to retain the array names. Try,
names = [[results valueForKey:#"name"] retain];
You could consider using declared properties to overcome the overhead of retaining and releasing the objects.
seems to be new bee. please check out for step by step tutorial
http://adeem.me/blog/2009/05/19/iphone-programming-tutorial-part-1-uitableview-using-nsarray/

Table View Crashing When Accessing Array of Dicitonarys

All,
When my table view loads, it accesses several delegate methods. When I configure the cell, I have it calling this method (where "linkedList" is an array of dictionarys):
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
VUWIManager *vuwiManager = [VUWIManager sharedVuwiManager];
NSLog(#"%#", [[vuwiManager linkedList]objectAtIndex:indexPath.row]);
NSLog(#"TESTZOMGOFDSOJFDSJFPODJSAPFDS");
cell.textLabel.text = [[vuwiManager linkedList]objectAtIndex:indexPath.row];
return cell;
}
It crashes at the line cell.textLabel.text = [[vuwiManager linkedList]objectAtIndex:indexPath.row]; - I know I'm doing something wrong here but I'm not sure what it is. Again, linkedList is a NSMutableArray of NSDictionarys.
Edit: if I call cell.textLabel.text = [[vuwiManager linkedList]objectAtIndex:indexPath.row]; it returns:
{
IP = "192.168.17.1";
desc = "description";
}
in the debugger. Just thought I'd give a little bit of formatting details.
Thanks
You are trying to assign an object NSDictionary to cell.textLabel.text, which must be passed a NSString.
Did you want :
NSString *s = [NSString stringWithFormat:#"%#",
[[vuwiManager linkedList]objectAtIndex:indexPath.row]];
cell.textLabel.text = s;
?
Setting an NSString * to an NSDictionary * will likely result in a crash when it tries to access any string methods that are not implemented in the dictionary. If you want that string you are logging add a call to description.
cell.textLabel.text = [[[vuwiManager linkedList]objectAtIndex:indexPath.row] description];
It looks like you are setting cell.textLabel.text to a NSDictionary instead of an NSString. If linkedList is an NSMutableArray of NSDictionaries, then you need to add on objectForKey:#"String key" to access the string
cell.textLabel.text = [[[vuwiManager linkedList]objectAtIndex:indexPath.row] objectForKey:#"STRING_KEY_HERE"];

iphone: UITABLEView crashing the application

dont know whats wrong with my table view, I have a dictionary(this dictionary is created by a sqlite operation) and I am trying to create cells like this
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = #"MyIdentifier";
MyIdentifier = #"tblCellView";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if(cell == nil) {
[[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil];
cell = aCustomCell;
aCustomCell=nil;
}
NSMutableDictionary *tempDictionary=[[NSMutableDictionary alloc] init];
tempDictionary=[offendersNamesList objectForKey:[NSString stringWithFormat:#"key%d", indexPath.row+1]];
[[cell offendersImageView] setImage:[UIImage imageNamed:#"contact.png"]];
[cell.offendersNameLbl setText:[tempDictionary objectForKey:#"name"]];
[cell.offendersViolation setText:[tempDictionary objectForKey:#"offence"]];
[tempDictionary release];
//[cell setLabelText:[arryData objectAtIndex:indexPath.row]];
return cell;
}
all the items are displayed correctly but when I scroll the table view up the application crashes can you help me in this?
You are first allocating a new NSMutableDictionary and store it in tempDictionary. However, in the very next line, you overwrite that variable with a pointer to a new object (tempDictionary=[offendersNamesList objectForKey:[NSString stringWithFormat:#"key%d", indexPath.row+1]];). So you've got a memory leak here, the [[NSMutableDictionary alloc] init] is unnecessary, remove it.
Now, due to the naming conventions, the object that you've got from the offendersNamesList is autoreleased, yet you later call [tempDictionary release]; and thus over-release it. Remove that as well.