AlAssetsLibrary issue, code works in 4.3 but not 5.0 - ios5

Here's my issue, if I access this class with iOS 4.X, the code works fine.... however whenever I try to access it with iOS 5.0, I get nil values for the groups & assets. What's the best way to get this to work? I'm posting the entire class for a reference...
.h
#import <UIKit/UIKit.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "DejViewController.h"
#class Event, Venue;
#interface SelectMediaViewController : DejViewController <UITableViewDelegate, UITableViewDataSource> {
Event *event;
Venue *venue;
UITableView *tableView;
NSMutableArray *selectedAssets;
NSMutableArray *allMedia;
ALAssetsLibrary *library;
NSMutableArray *assetGroups;
}
#property (nonatomic, retain) Event *event;
#property (nonatomic, retain) Venue *venue;
#property (nonatomic, retain) IBOutlet UITableView *tableView;
#property (nonatomic, retain) NSMutableArray *allMedia;
#property (nonatomic, retain) NSMutableArray *assetGroups;
- (IBAction)continuePressed:(id)sender;
#end
.m
#import <ImageIO/ImageIO.h>
#import "SelectMediaViewController.h"
#import "CaptionAllMediaViewController.h"
#import "MediaItem.h"
#import "CLValueButton.h"
#import "SelectMediaTableViewCell.h"
#define kMediaGridSize 75
#define kMediaGridPadding 4
#define kSelectImageTag 828
#interface SelectMediaViewController(Private)
- (void)setContentForButton:(CLValueButton *)button withAsset:(ALAsset *)asset;
- (void)loadData;
#end
#implementation SelectMediaViewController
#synthesize event, venue;
#synthesize tableView;
#synthesize allMedia,assetGroups;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
selectedAssets = [[NSMutableArray alloc] init];
showNextButton = YES;
}
return self;
}
- (void)dealloc {
[tableView release];
[event release];
[venue release];
[library release];
[allMedia release];
[selectedAssets release];
[assetGroups release];
[super dealloc];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"SelectMediaViewController - viewDidLoad");
}
- (void)viewDidUnload {
NSLog(#"SelectMediaViewController - viewDidUnload");
[self setTableView:nil];
[super viewDidUnload];
}
- (void)viewDidAppear:(BOOL)animated {
NSLog(#"SelectMediaViewController - viewDidAppear");
[super viewDidAppear:animated];
[self setNavTitle:#"Select Media"];
[self loadData];
[self.tableView reloadData];
float contentOffset = self.tableView.contentSize.height - self.tableView.frame.size.height;
if (contentOffset < 0) contentOffset = 0;
[self.tableView setContentOffset:CGPointMake(0, contentOffset) animated:NO];
}
- (void)viewDidDisappear:(BOOL)animated {
NSLog(#"SelectMediaViewController - viewDidDisappear");
self.allMedia = nil;
[selectedAssets removeAllObjects];
[self.tableView reloadData];
}
- (void)loadData {
NSMutableArray *tempArray = [[NSMutableArray array] init];
library = [[ALAssetsLibrary alloc] init];
void (^assetEnumerator)(ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
if(result != NULL) {
NSLog(#"See Asset: %#", result);
[tempArray addObject:result];
NSLog(#"assets count: %i", tempArray.count);
}
else {
NSLog(#"result nil or end of list");
}
};
void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop) {
if(group != nil) {
[group enumerateAssetsUsingBlock:assetEnumerator];
NSLog(#"group: %#",group);
}
else {
NSLog(#"group nil or end of list");
}
if (stop) {
self.allMedia = [NSMutableArray arrayWithCapacity:[tempArray count]];
self.allMedia = tempArray;
NSLog(#"Loaded data: %d & %d", [tempArray count], [self.allMedia count]);
}
};
//ALAssetsLibrary *library = [[[ALAssetsLibrary alloc] init] autorelease];
[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
usingBlock:assetGroupEnumerator
failureBlock:^(NSError *error) {
}];
//[library release];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (IBAction)continuePressed:(id)sender {
if ([selectedAssets count] > 0) {
CaptionAllMediaViewController *captionVC = [[CaptionAllMediaViewController alloc] initWithNibName:nil bundle:nil];
captionVC.event = self.event;
captionVC.venue = self.venue;
// Create media items
NSMutableArray *mediaItems = [NSMutableArray arrayWithCapacity:[selectedAssets count]];
for (ALAsset *asset in selectedAssets) {
MediaItem *item = [[MediaItem alloc] init];
item.asset = asset;
NSDictionary *metadata = [[asset defaultRepresentation] metadata];
NSDictionary *gpsMeta = [metadata objectForKey:#"{GPS}"];
if (gpsMeta) {
float latitude = [[gpsMeta objectForKey:#"Latitude"] floatValue];
if ([[gpsMeta objectForKey:#"LatitudeRef"] isEqualToString:#"S"]) latitude = latitude * -1;
float longitude = [[gpsMeta objectForKey:#"Longitude"] floatValue];
if ([[gpsMeta objectForKey:#"LongitudeRef"] isEqualToString:#"W"]) longitude = longitude * -1;
item.location = CLLocationCoordinate2DMake(latitude, longitude);
}
[mediaItems addObject:item];
[item release];
}
captionVC.media = mediaItems;
[self.navigationController pushViewController:captionVC animated:YES];
[captionVC release];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Images Selected"
message:#"Please select at least one image to continue."
delegate:nil
cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
}
- (void)imagePressed:(CLValueButton *)sender {
BOOL currentlySelected = [selectedAssets containsObject:sender.valueObject];
UIImageView *imageView = (UIImageView *)[sender viewWithTag:kSelectImageTag];
if (!currentlySelected) {
[imageView setImage:[UIImage imageNamed:#"image-select-active.png"]];
[selectedAssets addObject:sender.valueObject];
} else {
[imageView setImage:[UIImage imageNamed:#"image-select.png"]];
[selectedAssets removeObject:sender.valueObject];
}
}
#pragma Table view methods
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog(#"Getting table view count: %d", [self.allMedia count]);
if ([self.allMedia count] == 0) return 0;
return ceil([self.allMedia count] / 4.0);
}
- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 83;
NSLog(#"return83");
}
- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
SelectMediaTableViewCell *cell = (SelectMediaTableViewCell *)[_tableView dequeueReusableCellWithIdentifier:#"MEDIA_CELL"];
if (!cell) {
cell = [[[NSBundle mainBundle] loadNibNamed:#"SelectMediaTableViewCell" owner:nil options:nil] objectAtIndex:0];
// wire up selectors
[cell.image1 addTarget:self action:#selector(imagePressed:) forControlEvents:UIControlEventTouchUpInside];
[cell.image2 addTarget:self action:#selector(imagePressed:) forControlEvents:UIControlEventTouchUpInside];
[cell.image3 addTarget:self action:#selector(imagePressed:) forControlEvents:UIControlEventTouchUpInside];
[cell.image4 addTarget:self action:#selector(imagePressed:) forControlEvents:UIControlEventTouchUpInside];
}
int startIndex = indexPath.row * 4;
for (int i = 0; i < 4; i++) {
ALAsset *thisAsset = (startIndex + i) < [self.allMedia count] ? [self.allMedia objectAtIndex:startIndex + i] : nil;
CLValueButton *button = nil;
switch (i) {
case 0:
button = cell.image1;
break;
case 1:
button = cell.image2;
break;
case 2:
button = cell.image3;
break;
case 3:
button = cell.image4;
break;
default:
break;
}
[self setContentForButton:button withAsset:thisAsset];
UIImageView *imageView = (UIImageView *)[button viewWithTag:kSelectImageTag];
// letse see if it's selected or not...
if ([selectedAssets containsObject:button.valueObject]) {
[imageView setImage:[UIImage imageNamed:#"image-select-active.png"]];
} else {
[imageView setImage:[UIImage imageNamed:#"image-select.png"]];
}
}
return cell;
}
- (void)setContentForButton:(CLValueButton *)button withAsset:(ALAsset *)asset {
button.hidden = asset == nil;
if (asset) {
CGImageRef image = [asset thumbnail];
[button setImage:[UIImage imageWithCGImage:image] forState:UIControlStateNormal];
}
[button setValueObject:asset];
}
#pragma -
#end
Any help would be much appreciated, I've been trying to figure this out for 3 days...

The ALAssetsLibrary page in the online documentation now says "The lifetimes of objects you get back from a library instance are tied to the lifetime of the library instance."

Related

Implement MWFeedParser in a ViewController

I'm trying to use the MWFeedParser library in my app. On my homescreen, I have a view controller named NewsViewController.
In the MWFeedParser library, the root view controller is called RootViewController. I've tried to copy all the code from the RootViewController into the NewsViewController .H + .M and in IB I've linked the tableview to "dataSource" and "delegate". But when my app starts the tableview is empty.
Here's how to code looks like:
.H:
#import <UIKit/UIKit.h>
#import "MWFeedItem.h"
#import "MWFeedParser.h"
#interface NewsViewController : UITableViewController <MWFeedParserDelegate, UITableViewDelegate, UITableViewDataSource> {
// Parsing
MWFeedParser *feedParser;
NSMutableArray *parsedItems;
// Displaying
NSArray *itemsToDisplay;
NSDateFormatter *formatter;
IBOutlet UITableView *tableView;
}
// Properties
#property (nonatomic, retain) NSArray *itemsToDisplay;
#property (nonatomic, retain) IBOutlet UITableView *tableView;
-(IBAction)goHome;
#end
.M:
#import "NSString+HTML.h"
#import "MWFeedParser.h"
#import "DetailTableViewController.h"
#implementation NewsViewController
#synthesize itemsToDisplay, tableView;
#pragma mark -
#pragma mark View lifecycle
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"News", #"News");
self.tabBarItem.image = [UIImage imageNamed:#"icon_news"]; }
return self;
}
- (void)viewDidLoad
{
label.shadowOffset = CGSizeMake(0.0f, 1.0f);
label.textColor = [UIColor colorWithRed:0xB3/249.0 green:0xB3/252.0 blue:0xB3/253.0 alpha:1];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
// Date
// Setup
formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterShortStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
parsedItems = [[NSMutableArray alloc] init];
self.itemsToDisplay = [NSArray array];
// Refresh button
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self
action:#selector(refresh)];
// Parse
NSURL *feedURL = [NSURL URLWithString:#"http://www.mywebsite.com/feed/"];
feedParser = [[MWFeedParser alloc] initWithFeedURL:feedURL];
feedParser.delegate = self;
feedParser.feedParseType = ParseTypeFull; // Parse feed info and all items
feedParser.connectionType = ConnectionTypeAsynchronously;
[feedParser parse];
UIImage *someImage = [UIImage imageNamed:#"back_active1#2x.png"];
[button setBackgroundImage:someImage forState:UIControlStateHighlighted];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewDidAppear:(BOOL)animated {
static BOOL first = YES;
if (first) {
UIViewController *popup = [[Home1ViewController alloc] initWithNibName:#"Home1ViewController" bundle:nil];
[self presentViewController:popup animated:NO completion:nil];
first = NO;
}
}
#pragma mark -
#pragma mark Parsing
// Reset and reparse
- (void)refresh {
self.title = #"Refreshing...";
[parsedItems removeAllObjects];
[feedParser stopParsing];
[feedParser parse];
self.tableView.userInteractionEnabled = NO;
self.tableView.alpha = 0.3;
}
- (void)updateTableWithParsedItems {
self.itemsToDisplay = [parsedItems sortedArrayUsingDescriptors:
[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:#"date"
ascending:NO]]];
self.tableView.userInteractionEnabled = YES;
self.tableView.alpha = 1;
[self.tableView reloadData];
}
#pragma mark -
#pragma mark MWFeedParserDelegate
- (void)feedParserDidStart:(MWFeedParser *)parser {
NSLog(#"Started Parsing: %#", parser.url);
}
- (void)feedParser:(MWFeedParser *)parser didParseFeedInfo:(MWFeedInfo *)info {
NSLog(#"Parsed Feed Info: “%#”", info.title);
self.title = info.title;
}
- (void)feedParser:(MWFeedParser *)parser didParseFeedItem:(MWFeedItem *)item {
NSLog(#"Parsed Feed Item: “%#”", item.title);
if (item) [parsedItems addObject:item];
}
- (void)feedParserDidFinish:(MWFeedParser *)parser {
NSLog(#"Finished Parsing%#", (parser.stopped ? #" (Stopped)" : #""));
[self updateTableWithParsedItems];
}
- (void)feedParser:(MWFeedParser *)parser didFailWithError:(NSError *)error {
NSLog(#"Finished Parsing With Error: %#", error);
if (parsedItems.count == 0) {
self.title = #"Failed"; // Show failed message in title
} else {
// Failed but some items parsed, so show and inform of error
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Parsing Incomplete"
message:#"There was an error during the parsing of this feed. Not all of the feed items could parsed."
delegate:nil
cancelButtonTitle:#"Dismiss"
otherButtonTitles:nil];
[alert show];
}
[self updateTableWithParsedItems];
}
#pragma mark -
#pragma mark Table view data source
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return itemsToDisplay.count;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// Configure the cell.
MWFeedItem *item = [itemsToDisplay objectAtIndex:indexPath.row];
if (item) {
// Process
NSString *itemTitle = item.title ? [item.title stringByConvertingHTMLToPlainText] : #"[No Title]";
NSString *itemSummary = item.summary ? [item.summary stringByConvertingHTMLToPlainText] : #"[No Summary]";
// Set
cell.textLabel.font = [UIFont boldSystemFontOfSize:15];
cell.textLabel.text = itemTitle;
NSMutableString *subtitle = [NSMutableString string];
if (item.date) [subtitle appendFormat:#"%#: ", [formatter stringFromDate:item.date]];
[subtitle appendString:itemSummary];
cell.detailTextLabel.text = subtitle;
}
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Show detail
DetailTableViewController *detail = [[DetailTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
detail.item = (MWFeedItem *)[itemsToDisplay objectAtIndex:indexPath.row];
[self.navigationController pushViewController:detail animated:YES];
// Deselect
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#end
what you do is in feedparserDidFinish method , try to reload table....like below...
- (void)feedParserDidFinish:(MWFeedParser *)parser {
NSLog(#"Finished Parsing%#", (parser.stopped ? #" (Stopped)" : #""));
[self.tableView reloadData];
}
let me know it is working or not!!!!!
Happy Coding!!!!!!!

Error when implementing MWFeedParser

I trying to use the MWFeedParser library. I think the problem is that I want to use a view controller with a table view to display the news. Now there comes nothing up in my table view when launching the app. The code for the news view controller looks like this:
.H:
#import "MWFeedItem.h"
#import "MWFeedParser.h"
#interface NewsViewController : UIViewController <MWFeedParserDelegate> {
IBOutlet UILabel *label;
// Parsing
MWFeedParser *feedParser;
NSMutableArray *parsedItems;
// Displaying
NSArray *itemsToDisplay;
NSDateFormatter *formatter;
IBOutlet UITableView *tableView;
}
// Properties
#property (nonatomic, retain) NSArray *itemsToDisplay;
#property (nonatomic, retain) IBOutlet UITableView *tableView;
#end
.M:
#import "NSString+HTML.h"
#import "MWFeedParser.h"
#import "DetailTableViewController.h"
#implementation NewsViewController
#synthesize itemsToDisplay, tableView;
#pragma mark -
#pragma mark View lifecycle
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"News", #"News");
self.tabBarItem.image = [UIImage imageNamed:#"icon_news"]; }
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
// Date
// Setup
self.title = #"News";
formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterShortStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
parsedItems = [[NSMutableArray alloc] init];
self.itemsToDisplay = [NSArray array];
// Refresh button
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self
action:#selector(refresh)];
// Parse
NSURL *feedURL = [NSURL URLWithString:#"http://www.website.com/feed/"];
feedParser = [[MWFeedParser alloc] initWithFeedURL:feedURL];
feedParser.delegate = self;
feedParser.feedParseType = ParseTypeFull; // Parse feed info and all items
feedParser.connectionType = ConnectionTypeAsynchronously;
[feedParser parse];
UIImage *someImage = [UIImage imageNamed:#"back_active1#2x.png"];
[button setBackgroundImage:someImage forState:UIControlStateHighlighted];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewDidAppear:(BOOL)animated {
static BOOL first = YES;
if (first) {
UIViewController *popup = [[Home1ViewController alloc] initWithNibName:#"Home1ViewController" bundle:nil];
[self presentViewController:popup animated:NO completion:nil];
first = NO;
}
}
#pragma mark -
#pragma mark Parsing
// Reset and reparse
- (void)refresh {
self.title = #"Refreshing...";
[parsedItems removeAllObjects];
[feedParser stopParsing];
[feedParser parse];
/*
self.tableView.userInteractionEnabled = NO;
self.tableView.alpha = 0.3;
*/
}
- (void)updateTableWithParsedItems {
self.itemsToDisplay = [parsedItems sortedArrayUsingDescriptors:
[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:#"date"
ascending:NO]]];
/* self.tableView.userInteractionEnabled = YES;
self.tableView.alpha = 1;
[self.tableView reloadData];
*/
}
#pragma mark -
#pragma mark MWFeedParserDelegate
- (void)feedParserDidStart:(MWFeedParser *)parser {
NSLog(#"Started Parsing: %#", parser.url);
}
- (void)feedParser:(MWFeedParser *)parser didParseFeedInfo:(MWFeedInfo *)info {
NSLog(#"Parsed Feed Info: “%#”", info.title);
self.title = info.title;
}
- (void)feedParser:(MWFeedParser *)parser didParseFeedItem:(MWFeedItem *)item {
NSLog(#"Parsed Feed Item: “%#”", item.title);
if (item) [parsedItems addObject:item];
}
- (void)feedParserDidFinish:(MWFeedParser *)parser {
NSLog(#"Finished Parsing%#", (parser.stopped ? #" (Stopped)" : #""));
[self updateTableWithParsedItems];
}
- (void)feedParser:(MWFeedParser *)parser didFailWithError:(NSError *)error {
NSLog(#"Finished Parsing With Error: %#", error);
if (parsedItems.count == 0) {
self.title = #"Failed"; // Show failed message in title
} else {
// Failed but some items parsed, so show and inform of error
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Parsing Incomplete"
message:#"There was an error during the parsing of this feed. Not all of the feed items could parsed."
delegate:nil
cancelButtonTitle:#"Dismiss"
otherButtonTitles:nil];
[alert show];
}
[self updateTableWithParsedItems];
}
#pragma mark -
#pragma mark Table view data source
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return itemsToDisplay.count;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// Configure the cell.
MWFeedItem *item = [itemsToDisplay objectAtIndex:indexPath.row];
if (item) {
// Process
NSString *itemTitle = item.title ? [item.title stringByConvertingHTMLToPlainText] : #"[No Title]";
NSString *itemSummary = item.summary ? [item.summary stringByConvertingHTMLToPlainText] : #"[No Summary]";
// Set
cell.textLabel.font = [UIFont boldSystemFontOfSize:15];
cell.textLabel.text = itemTitle;
NSMutableString *subtitle = [NSMutableString string];
if (item.date) [subtitle appendFormat:#"%#: ", [formatter stringFromDate:item.date]];
[subtitle appendString:itemSummary];
cell.detailTextLabel.text = subtitle;
}
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Show detail
DetailTableViewController *detail = [[DetailTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
detail.item = (MWFeedItem *)[itemsToDisplay objectAtIndex:indexPath.row];
[self.navigationController pushViewController:detail animated:YES];
// Deselect
[self->tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#end
In IB, I've dragged a table view onto the view and linked it to dataSource and delegate. But nothing shows up in the table view.
Would really appreciate some answers/ideas!
Thanks.
i think you should uncomment the following line in your "updateTableWithParsedItems" method:
[self.tableView reloadData];

Populating UITableView dynamically

I have the following code to fetch the data from URL, store it in arrays, and display it inside the table.
Now the issue is my URL which is feeding data to the tables changes according to the button click i.e. If user clicks button [gainer], data gets fetched from URL related to gainer and so on.
As I have called gainer method in didLoad method, initially data is displayed from the respective URL.But on button click no action is taken. The reason is I'm populating the arrays in methods (gainer and looser) but table is fetching data from the arrays at the time of table creation(and arrays are empty at that point).
I have created button in design view while I'm creating table programmatically.
fetchdataViewController.h
#import <UIKit/UIKit.h>
#interface fetchdataViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>{
IBOutlet UIWebView *webView;
NSMutableArray *arr1;
NSMutableArray *atarr;
NSMutableArray *arr2;
NSMutableArray *a;
NSMutableArray *b;
NSMutableArray *c;
NSMutableArray *d;
UITableView *aTableView;
}
-(IBAction)btnClicked:(id)sender;
-(IBAction)btnClicked1:(id)sender;
-(void)gainer;
-(void)looser;
#property(nonatomic,retain)NSMutableArray *arr1;
#property(nonatomic,retain)NSMutableArray *arr2;
#property(nonatomic,retain)NSMutableArray *atarr;
#property(nonatomic,retain)NSMutableArray *a;
#property(nonatomic,retain)NSMutableArray *b;
#property(nonatomic,retain)NSMutableArray *c;
#property(nonatomic,retain)NSMutableArray *d;
#property(nonatomic,retain)UIWebView *webView;
#property(nonatomic,retain)UITableView *aTableView;
#end
fetchdataViewController.m
#import "fetchdataViewController.h"
#implementation fetchdataViewController
NSMutableArray *atarr;
NSMutableArray *arr1;
NSMutableArray *arr2;
NSMutableArray *a;
NSMutableArray *b;
NSMutableArray *c;
NSMutableArray *d;
NSMutableString *mainstr;
NSMutableString *str;
#synthesize webView;
#synthesize arr1;
#synthesize arr2;
#synthesize atarr;
#synthesize a;
#synthesize b;
#synthesize c;
#synthesize d;
#synthesize aTableView;
int i,j;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [a count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier=#"Cell";
static NSInteger StateTag = 1;
static NSInteger CapitalTag = 2;
static NSInteger StateTag1 = 3;
static NSInteger StateTag2 = 4;
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil){
cell=[[[UITableViewCell alloc]initWithFrame:CGRectZero reuseIdentifier:CellIdentifier]autorelease];
CGRect frame;
frame.origin.x = 10;
frame.origin.y = 5;
frame.size.height = 35;
frame.size.width = 170;
UILabel *capitalLabel = [[UILabel alloc] initWithFrame:frame];
capitalLabel.tag = CapitalTag;
[cell.contentView addSubview:capitalLabel];
frame.origin.x += 125;
UILabel *stateLabel = [[UILabel alloc] initWithFrame:frame];
stateLabel.tag = StateTag;
[cell.contentView addSubview:stateLabel];
frame.origin.x += 100;
UILabel *stateLabel1 = [[UILabel alloc] initWithFrame:frame];
stateLabel1.tag = StateTag1;
[cell.contentView addSubview:stateLabel1];
frame.origin.x += 100;
UILabel *stateLabel2 = [[UILabel alloc] initWithFrame:frame];
stateLabel2.tag = StateTag2;
[cell.contentView addSubview:stateLabel2];
}
UILabel *capitalLabel = (UILabel *) [cell.contentView viewWithTag:CapitalTag];
UILabel *stateLabel = (UILabel *) [cell.contentView viewWithTag:StateTag];
UILabel *stateLabel1 = (UILabel *) [cell.contentView viewWithTag:StateTag1];
UILabel *stateLabel2 = (UILabel *) [cell.contentView viewWithTag:StateTag2];
capitalLabel.text=[a objectAtIndex:indexPath.row];
stateLabel.text = [b objectAtIndex:indexPath.row];
stateLabel1.text = [c objectAtIndex:indexPath.row];
stateLabel2.text = [d objectAtIndex:indexPath.row];
return cell;
}
-(IBAction)btnClicked:(id)sender{
[self gainer];
}
-(IBAction)btnClicked1:(id)sender {
[self looser];
}
-(void)gainer{
arr1=[[NSMutableArray alloc]init];
arr2=[[NSMutableArray alloc]init];
a=[[NSMutableArray alloc]init];
b=[[NSMutableArray alloc]init];
c=[[NSMutableArray alloc]init];
d=[[NSMutableArray alloc]init];
NSURL *url=[NSURL URLWithString:#"http://ipad.idealake.com/default.aspx?id=G"];
NSURLRequest *req=[NSURLRequest requestWithURL:url];
[webView loadRequest:req];
//storing page data in string
mainstr=[[NSMutableString alloc] initWithContentsOfURL:url];
atarr=[mainstr componentsSeparatedByString:#"#"];
NSString *str2;
NSString *str3;
for(int i=0; i<[atarr count]-1; i++)
{
// NSLog(#"i=:%i",i);
NSMutableString *str = [atarr objectAtIndex:i];
if (str!= nil)
arr1=[str componentsSeparatedByString:#";"];
for (int k=0;k<[arr1 count];k++)
{
str2 = [arr1 objectAtIndex:k];
[arr2 addObject:str2];
}
}
else
{
//NSLog (#"Nill");
}
}
for(int l=0;l<[arr2 count]/4;l++){
str3=[arr2 objectAtIndex:4*l];
[a addObject:str3];
str3=[arr2 objectAtIndex:(4*l)+1];
[b addObject:str3];
str3=[arr2 objectAtIndex:(4*l)+2];
[c addObject:str3];
str3=[arr2 objectAtIndex:(4*l)+3];
[d addObject:str3];
}
}
-(void)looser{
arr1=[[NSMutableArray alloc]init];
arr2=[[NSMutableArray alloc]init];
a=[[NSMutableArray alloc]init];
b=[[NSMutableArray alloc]init];
c=[[NSMutableArray alloc]init];
d=[[NSMutableArray alloc]init];
NSURL *url=[NSURL URLWithString:#"http://ipad.idealake.com/default.aspx?id=L"];
NSURLRequest *req=[NSURLRequest requestWithURL:url];
[webView loadRequest:req];
mainstr=[[NSMutableString alloc] initWithContentsOfURL:url];
atarr=[mainstr componentsSeparatedByString:#"#"];
NSString *str2;
NSString *str3;
for(int i=0; i<[atarr count]-1; i++)
{
NSMutableString *str = [atarr objectAtIndex:i];
if (str!= nil)
{
arr1=[str componentsSeparatedByString:#";"];
for (int k=0;k<[arr1 count];k++)
{
str2 = [arr1 objectAtIndex:k];
[arr2 addObject:str2];
}
}
else
{
//NSLog (#"Nill");
}
}
for(int l=0;l<[arr2 count]/4;l++){
str3=[arr2 objectAtIndex:4*l];
[a addObject:str3];
str3=[arr2 objectAtIndex:(4*l)+1];
[b addObject:str3];
str3=[arr2 objectAtIndex:(4*l)+2];
[c addObject:str3];
str3=[arr2 objectAtIndex:(4*l)+3];
[d addObject:str3];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
arr1=[[NSMutableArray alloc]init];
arr2=[[NSMutableArray alloc]init];
a=[[NSMutableArray alloc]init];
b=[[NSMutableArray alloc]init];
c=[[NSMutableArray alloc]init];
d=[[NSMutableArray alloc]init];
[self gainer];
[super viewDidLoad];
aTableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen]applicationFrame] style:UITableViewStyleGrouped];
aTableView.dataSource = self;
aTableView.delegate = self;
aTableView.frame = CGRectMake(0, 10, 720, 500);
[self.view addSubview:aTableView];
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return YES;
}
#end
UPDATE
When I run the below code, I get this output. That shaded grey portion is my main concern.
THANKS IN ADVANCE
You need to tell your UITableView that the data has changed by calling reloadData.
Use [self.tableview reloadData] after each change of url and with new arrays filled.

how to select multiple data from multiple rows in custom cell in xcode?

code:
check it:
#import <UIKit/UIKit.h>
#interface addsymptom : UITableViewController<UITableViewDelegate, UITableViewDataSource> {
NSMutableArray *listData;
}
#property(nonatomic,retain)NSMutableArray *listData;
#end
data.m:
============
#import "CustomCell.h"
#implementation addsymptom
#synthesize listData;
- (void)viewDidLoad
{
self.navigationItem.title= #"Symptoms";
self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"mainbg.png"]];
listData =[[NSMutableArray alloc] init];
[listData addObject:#"Backpain"];
[listData addObject:#"headache"];
[listData addObject:#"vomitting"];
[listData addObject:#"Bodypain"];
[listData addObject:#"thursday"];
[listData addObject:#"maleria"];
[listData addObject:#"Food poisioning"];
UIBarButtonItem *saveButton=[[UIBarButtonItem alloc]initWithTitle:#"save"
style:UIBarButtonSystemItemDone
target:self
action:#selector(save)];
self.navigationItem.rightBarButtonItem = saveButton;
[saveButton release];
[super viewDidLoad];
}
-(void)save {
[self.navigationController popViewControllerAnimated:YES];
}
- (UITableViewCell *)tableView:(UITableView *) tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CustomCell";
CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil];
for (id currentObject in topLevelObjects){
if ([currentObject isKindOfClass:[UITableViewCell class]]){
cell = (CustomCell *) currentObject;
break;
}
}
}
cell.textLabel.text = [listData objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc. that aren't in use.
}
- (void)viewDidUnload
{
self.listData = nil;
}
- (void)dealloc
{
[super dealloc];
}
#end
custom cell.h:
==========
#import <Foundation/Foundation.h>
#interface CustomCell :UITableViewCell {
IBOutlet UILabel *textLabel;
IBOutlet UIButton *bttn;
BOOL isChecked;
NSString *ans;
}
#property (nonatomic,retain) IBOutlet UILabel *textLabel;
#property (nonatomic,assign) BOOL isChecked;
#property(nonatomic,assign)IBOutlet UIButton *bttn;
-(void)checkBoxClicked:(id)sender;
#end
customcell.m:
==============
#import "CustomCell.h"
#implementation CustomCell
#synthesize textLabel,bttn,isChecked;
-(id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithFrame:frame ]) {
textLabel = [[UILabel alloc]init];
textLabel.textAlignment = UITextAlignmentLeft;
}
return self;
}
NSString *ABC=NULL;
NSString *xyz=NULL;
-(void)checkBoxClicked:(id)sender{
UIButton *tappedButton = (UIButton*)sender;
if([tappedButton.currentImage isEqual:[UIImage imageNamed:#"NotSelected.png"]]) {
[sender setImage:[UIImage imageNamed: #"IsSelected.png"] forState:UIControlStateNormal];
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Message"
message:textLabel.text
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil,nil]autorelease];
[alert show];
ans = textLabel.text;
NSLog(#"%#",ans);
}
else {
[sender setImage:[UIImage imageNamed:#"NotSelected.png"]forState:UIControlStateNormal];
}
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
}
- (void)dealloc {
[super dealloc];
}
#end
check this example it has some implementation like yours
http://cocoawithlove.com/2009/01/multiple-row-selection-and-editing-in.html
best of luck
//CustomCell.h
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#interface CustomCell :UITableViewCell {
IBOutlet UILabel *textLabel;
IBOutlet UIButton *bttn;
BOOL isChecked;
NSString *ans;
}
#property (nonatomic,retain) IBOutlet UILabel *textLabel;
#property (nonatomic,assign) BOOL isChecked;
#property(nonatomic,assign)IBOutlet UIButton *bttn;
//-(void)checkBoxClicked:(id)sender;
#end
//CustomCell.m
#import "CustomCell.h"
#implementation CustomCell
#synthesize textLabel,bttn,isChecked;
-(id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithFrame:frame ]) {
textLabel = [[UILabel alloc]init];
textLabel.textAlignment = UITextAlignmentLeft;
}
return self;
}
NSString *ABC=NULL;
NSString *xyz=NULL;
//-(void)checkBoxClicked:(id)sender{
//
// UIButton *tappedButton = (UIButton*)sender;
//
//
// if([tappedButton.currentImage isEqual:[UIImage imageNamed:#"chkbox_unckd.png"]]) {
// [sender setImage:[UIImage imageNamed: #"chkbox_ckd.png"] forState:UIControlStateNormal];
// UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Message"
// message:textLabel.text
// delegate:self
// cancelButtonTitle:#"OK"
// otherButtonTitles:nil,nil]autorelease];
// [alert show];
//
// ans = textLabel.text;
//
//
// NSLog(#"%#",ans);
//
//
// }
//
// else {
// [sender setImage:[UIImage imageNamed:#"chkbox_unckd.png"]forState:UIControlStateNormal];
// }
//
//
//
//}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
// [bttn setImage:[UIImage imageNamed:#"chkbox_ckd.png"] forState:UIControlStateNormal];
[super setSelected:selected animated:animated];
}
- (void)dealloc {
[super dealloc];
}
#end
//addsymptom.h
#import <UIKit/UIKit.h>
#interface addsymptom : UIViewController<UITableViewDelegate, UITableViewDataSource> {
NSMutableArray *listData;
IBOutlet UITableView *table;
NSMutableArray *TitlesArray;
NSMutableArray *isCheckedArr;
}
#property(nonatomic,retain)NSMutableArray *listData;
- (void)saveTheChanges;
#end
//addsymptom.m
#import "addsymptom.h"
#import "CustomCell.h"
#implementation addsymptom
#synthesize listData;
- (void)viewDidLoad
{
self.navigationItem.title= #"Symptoms";
self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"mainbg.png"]];
listData =[[NSMutableArray alloc] init];
[listData addObject:#"Backpain"];
[listData addObject:#"headache"];
[listData addObject:#"vomitting"];
[listData addObject:#"Bodypain"];
[listData addObject:#"thursday"];
[listData addObject:#"maleria"];
[listData addObject:#"Food poisioning"];
UIBarButtonItem *saveButton=[[UIBarButtonItem alloc]initWithTitle:#"save" style:UIBarButtonSystemItemDone target:self action:#selector(saveTheChanges)];
isCheckedArr = [[NSMutableArray alloc] init];
for (int i=0; i<[listData count]; i++) {
[isCheckedArr addObject:#"0"];
}
self.navigationItem.rightBarButtonItem = saveButton;
[saveButton release];
TitlesArray = [[NSMutableArray alloc] init];
}
-(void)save {
[self.navigationController popViewControllerAnimated:YES];
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [listData count];
}
- (UITableViewCell *)tableView:(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CustomCell";
CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil];
for (id currentObject in topLevelObjects){
if ([currentObject isKindOfClass:[UITableViewCell class]]){
cell = (CustomCell *) currentObject;
break;
}
}
}
cell.textLabel.text = [listData objectAtIndex:indexPath.row];
[cell.bttn setTag:indexPath.row];
[cell.bttn addTarget:self action:#selector(updateCheckbox:) forControlEvents:UIControlEventTouchUpInside];
if ([[isCheckedArr objectAtIndex:indexPath.row] isEqualToString:#"1"])
{
[cell.bttn setImage:[UIImage imageNamed:#"chkbox_ckd.png"] forState:UIControlStateNormal];
}
else
{
[cell.bttn setImage:[UIImage imageNamed:#"chkbox_unckd.png"] forState:UIControlStateNormal];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
- (void)updateCheckbox:(id)sender {
if ([[isCheckedArr objectAtIndex:[sender tag]] isEqualToString:#"0"]) {
[isCheckedArr replaceObjectAtIndex:[sender tag] withObject:#"1"];
}
else if ([[isCheckedArr objectAtIndex:[sender tag]] isEqualToString:#"1"]) {
[isCheckedArr replaceObjectAtIndex:[sender tag] withObject:#"0"];
for (int i=0; i<[TitlesArray count]; i++) {
if ([[listData objectAtIndex:[sender tag]] isEqualToString:[TitlesArray objectAtIndex:i]]) {
[TitlesArray removeObjectAtIndex:i];
}
}
}
[table reloadData];
}
- (void)saveTheChanges {
for (int i=0; i<[isCheckedArr count]; i++) {
if ([[isCheckedArr objectAtIndex:i] isEqualToString:#"1"]) {
for (int j=0; j<[TitlesArray count]; j++) {
if ([[listData objectAtIndex:i] isEqualToString:[TitlesArray objectAtIndex:j]]) {
[TitlesArray removeObjectAtIndex:j];
}
}
[TitlesArray addObject:[listData objectAtIndex:i]];
}
}
for (int i=0; i<[TitlesArray count]; i++) {
NSLog(#"%#",[TitlesArray objectAtIndex:i]);
}
NSLog(#"=======");
}
- (void)viewDidUnload
{
// self.listData = nil;
}
- (void)dealloc
{
[listData release];
[TitlesArray release];
[isCheckedArr release];
[super dealloc];
}
#end
Does this post help, if you want Mail app style multiple selection of cells? Another post with great answers.

Strange crash (EXC_BAD_ACCESS) scrolling UITableView reentering app after background

I'm using an UITableView with standard cell with subtitle and UIImageView. The scrolling is ok till I exit from the app. Then it goes background (I make nothing on delegate backgroun methods) and when I rerun the app, on the same view with the uitable, the scroll it's ok for some rows then the app crash in the method:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
the code of the method is:
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
ALog(#"TRACE");
}
// Configure the cell...
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
NSDictionary *cellContent = (NSDictionary *)[self.items objectAtIndex:indexPath.row];
Restaurant * r = (Restaurant *)[cellContent valueForKey:#"ristorante"];
cell.textLabel.textColor = [UIColor colorWithRed:245.0 green:245.0 blue:245.0 alpha:0.8];
cell.textLabel.text = r.nome;
cell.detailTextLabel.textColor = [UIColor lightTextColor];
cell.detailTextLabel.text = [r.indirizzo convertToString];
UIImage *img = r.tipo.image; //[UIImage imageNamed:#"loghetto_pne.png"];
cell.imageView.image = img;
//cell.imageView.clipsToBounds = YES;
//cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
float sw= 48/img.size.width;
float sh= 48/img.size.height;
cell.imageView.transform = CGAffineTransformMakeScale(sw,sh);
//[img release];
return cell;
The crash is in the line:
cell.imageView.image = img;
From the stack trace I see that the execution goes on some internal framework code and then crash. The exception is not always the same (often is CATransaction count --> object di not respond to selector etc)
The code for Restaurant and Tipologia:
#import <Foundation/Foundation.h>
#class Zona;
#class Indirizzo;
#class Tipologia;
#interface Restaurant : NSObject {
#private
NSUInteger idx;
NSString *nome;
NSString *telefono;
Indirizzo *indirizzo;
Zona *zona;
Tipologia *tipo;
}
-(id)initWithIdx:(NSUInteger)index name:(NSString *)ristoName tel:(NSString *)ristoTel address:(Indirizzo *)ristoAdd zone:(Zona *)ristoZone;
#property (nonatomic) NSUInteger idx;
#property (nonatomic,retain) NSString *nome;
#property (nonatomic,retain) NSString *telefono;
#property (nonatomic,retain) Indirizzo *indirizzo;
#property (nonatomic,retain) Zona *zona;
#property (nonatomic,retain) Tipologia *tipo;
#end
Restaurant implementation:
#import "Restaurant.h"
#import "Zona.h"
#import "Indirizzo.h"
#import "Macro.h"
#implementation Restaurant
#synthesize idx, nome, indirizzo, telefono, zona, tipo;
-(id)initWithIdx:(NSUInteger)index name:(NSString *)ristoName tel:(NSString *)ristoTel address:(Indirizzo *)ristoAdd zone:(Zona *)ristoZone {
[self init];
bool error = NO;
if (self) {
idx = index;
nome = [ristoName retain];
telefono = [ristoTel retain];
indirizzo = [ristoAdd retain];
zona = [ristoZone retain];
}
return (error) ? nil : self;
}
- (id)init {
self = [super init];
if (self) {
idx = 0;
nome = #"";
telefono = #"";
indirizzo = nil;
zona = nil;
tipo = nil;
}
return self;
}
- (void)dealloc {
[nome release];
[indirizzo release];
[telefono release];
[zona release];
ALog(#"TRACE");
[tipo release];
ALog(#"TRACE");
[super dealloc];
}
#end
Tipologia interface and implementation:
#import <Foundation/Foundation.h>
typedef enum {
kTipoRestUnknown = 0,
kTipoRestRestaurant,
kTipoRestBrunch,
kTipoRestPizza,
kTipoRestRegional,
kTipoRestEthnic
} TipoRest;
#class ImageTest;
#interface Tipologia : NSObject {
#private
NSInteger idx;
NSString *desc;
UIImage *image;
TipoRest type;
}
-(id)initWithIndex:(NSInteger) index description:(NSString *)descr ofType:(TipoRest) type;
#property (nonatomic) NSInteger idx;
#property (nonatomic) TipoRest type;
#property (nonatomic,retain) NSString *desc;
#property (nonatomic,retain) UIImage *image;
#end
#import "Tipologia.h"
#import "Macro.h"
#implementation Tipologia
#synthesize desc, idx, image, type;
#pragma mark -
#pragma mark Memory Management
-(id)initWithIndex:(NSInteger) index description:(NSString *)descr ofType:(TipoRest) type {
self = [super init];
if (self != nil) {
self.idx = index;
self.desc = descr;
self.image = [UIImage imageNamed:#"immagineNA.png"];;
self.type = type;
}
return self;
}
-(void)dealloc {
[desc release];
desc = nil;
ALog(#"TRACE");
[image release];
image = nil;
ALog(#"TRACE");
[super dealloc];
}
-(void)release {
ALog(#"tipo.idx: %i, tipo.count: %i, tipo.imag: %#, tipo.img.count: %i", idx, [self retainCount], image, [image retainCount]);
[super release];
}
EDIT 2 Some other code. The snippet where I initialize the images based on the type
if (sqlite3_prepare_v2(db, queryStrTipo, -1, &query, NULL) == SQLITE_OK) {
restImage = [UIImage imageNamed:#"rest.png"];
pizzaImage = [UIImage imageNamed:#"pizza.png"];
etnImage = [UIImage imageNamed:#"etnico.png"];
brunchImage = [UIImage imageNamed:#"wineglass-blue.png"];
while(sqlite3_step(query) == SQLITE_ROW) {
NSString *desc = [NSString stringWithUTF8String:(char *)sqlite3_column_text(query, 1)];
tipo = [[Tipologia alloc] initWithIndex:sqlite3_column_int(query, 0)
description:desc ofType:kTipoRestUnknown];
ALog(#"tipo.idx: %i, retain count: %i",tipo.idx, [tipo retainCount]);
if ([desc compare:kTipoDescRestaurant options:NSCaseInsensitiveSearch] == NSOrderedSame) {
tipo.type = kTipoRestRestaurant;
tipo.image = restImage;
} else
if ([desc compare:kTipoDescPizza options:NSCaseInsensitiveSearch] == NSOrderedSame) {
tipo.type = kTipoRestPizza;
tipo.image = pizzaImage;
} else
if ([desc compare:kTipoDescEtnico options:NSCaseInsensitiveSearch] == NSOrderedSame) {
tipo.type = kTipoRestEthnic;
tipo.image = etnImage;
} else
if ([desc compare:kTipoDescBrunch options:NSCaseInsensitiveSearch] == NSOrderedSame) {
tipo.type = kTipoRestBrunch;
tipo.image = brunchImage;
} else
if ([desc compare:kTipoDescRegionale options:NSCaseInsensitiveSearch] == NSOrderedSame) {
tipo.type = kTipoRestRegional;
}
dictionary = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithInt:tipo.idx], #"index", tipo.desc, #"desc", nil];
[listaTipologie addObject:tipo];
[listaTemp addObject:dictionary];
ALog(#"tipo.idx: %i, retain count: %i",tipo.idx, [tipo retainCount]);
[tipo release];
[dictionary release];
}
[restImage release];
[pizzaImage release];
[etnImage release];
[brunchImage release];
}
You are missing a retain on either r.tipo, or r.tipo.image.
if they are both synthesized properties, check that the property declaration contains a retain.
If you implemented you own getters and/or setters, check that you are retaining and releasing everything properly.
Edit:
I just saw the new code you posted. Your problem is you are releasing UIImages that your code does not own. Excluding all the conditional logic you basically do this:
//Incorrect
UIImage *myImagename = [UIImage imageNamed:#"foo.png"]
yourclass.image = restImage;
[myImagename release];
This is incorrect because you never called alloc, copy or retain on the myImage object. [UIImage imageMamed] returns an autoreleased instance of a UIImage. It is the same as doing this (also incorrect):
//Incorrect
UIImage *myImagename = [[UIImage alloc] initWithImage:#"foo.png"] autorelease];
yourclass.image = restImage;
[myImagename release];
You have two options. Either manage the release yourself:
UIImage *myImagename = [UIImage alloc] initWithImage:#"foo.png"];
yourclass.image = restImage;
[myImagename release];
Or let the autoreleased object do its thing:
UIImage *myImagename = [UIImage imageNamed:#"foo.png"]
yourclass.image = restImage;
//Note: no release needed on yourClass.
In your specific code, you can take the second approach and it will look like this:
if (sqlite3_prepare_v2(db, queryStrTipo, -1, &query, NULL) == SQLITE_OK) {
restImage = [UIImage imageNamed:#"rest.png"];
pizzaImage = [UIImage imageNamed:#"pizza.png"];
etnImage = [UIImage imageNamed:#"etnico.png"];
brunchImage = [UIImage imageNamed:#"wineglass-blue.png"];
while(sqlite3_step(query) == SQLITE_ROW) {
NSString *desc = [NSString stringWithUTF8String:(char *)sqlite3_column_text(query, 1)];
tipo = [[Tipologia alloc] initWithIndex:sqlite3_column_int(query, 0)
description:desc ofType:kTipoRestUnknown];
ALog(#"tipo.idx: %i, retain count: %i",tipo.idx, [tipo retainCount]);
if ([desc compare:kTipoDescRestaurant options:NSCaseInsensitiveSearch] == NSOrderedSame) {
tipo.type = kTipoRestRestaurant;
tipo.image = restImage;
} else
if ([desc compare:kTipoDescPizza options:NSCaseInsensitiveSearch] == NSOrderedSame) {
tipo.type = kTipoRestPizza;
tipo.image = pizzaImage;
} else
if ([desc compare:kTipoDescEtnico options:NSCaseInsensitiveSearch] == NSOrderedSame) {
tipo.type = kTipoRestEthnic;
tipo.image = etnImage;
} else
if ([desc compare:kTipoDescBrunch options:NSCaseInsensitiveSearch] == NSOrderedSame) {
tipo.type = kTipoRestBrunch;
tipo.image = brunchImage;
} else
if ([desc compare:kTipoDescRegionale options:NSCaseInsensitiveSearch] == NSOrderedSame) {
tipo.type = kTipoRestRegional;
}
dictionary = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithInt:tipo.idx], #"index", tipo.desc, #"desc", nil];
[listaTipologie addObject:tipo];
[listaTemp addObject:dictionary];
ALog(#"tipo.idx: %i, retain count: %i",tipo.idx, [tipo retainCount]);
[tipo release];
[dictionary release];
}
}
Remember, the golden rule of iOS memory management:
If you use any method with the word copy, alloc, or new, you need to have a corresponding release.
And, of course, Apple's Memory Management Programming Guide is the definitive resourse
I resolved the issue.
UIImage imageNamed return an autorelease object (I didn't know about it) and I use it to alloc the 4 image variables that then will be assigned to the property (via . sintax) and I release them after assigning.
Build & Analyze told me that the release statement could be wrong cause I didn't own the object anymore. Commented it out and the crash goes out...
The fault lines was the last in "EDIT 2" snippet of my question.
Thanks to all.