Three20 to save images?(Close) - iphone

i'm a new iPhone application developer,i need create one application like photo gallery.Now my problem is i donno how to save a image to photo album.
i have build my project is no error no werning to me.in my simulator can run the project.
But i cnt see any things i add.Hope can help me.Thanks.
my code here.
Three20PhotoDemoAppDelegate.h
#import <UIKit/UIKit.h>
#interface Three20PhotoDemoAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#end
Three20PhotoDemoAppDelegate.m
#import "Three20PhotoDemoAppDelegate.h"
#import "AlbumController.h"
#import <Three20/Three20.h>
#implementation Three20PhotoDemoAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch
TTNavigator* navigator = [TTNavigator navigator];
TTURLMap* map = navigator.URLMap;
[map from:#"demo://album" toViewController: [AlbumController class]];
[navigator openURLAction:[TTURLAction actionWithURLPath:#"demo://album"]];
return YES;
}
- (BOOL)application:(UIApplication*)application handleOpenURL:(NSURL*)URL {
[[TTNavigator navigator] openURLAction:[TTURLAction actionWithURLPath:URL.absoluteString]];
return YES;
}
- (void)dealloc {
[super dealloc];
}
#end
PhotoSource.h
#import <Three20/Three20.h>
#import <Three20/Three20+Additions.h>
typedef enum {
PhotoSourceNormal = 0,
PhotoSourceDelayed = 1,
PhotoSourceVariableCount = 2,
PhotoSourceLoadError = 4,
} PhotoSourceType;
#interface PhotoSource : TTURLRequestModel <TTPhotoSource> {
PhotoSourceType _type;
NSString* _title;
NSMutableArray* _photos;
NSArray* _tempPhotos;
NSTimer* _fakeLoadTimer;
}
- (id)initWithType:(PhotoSourceType)type title:(NSString*)title
photos:(NSArray*)photos photos2:(NSArray*)photos2;
#end
PhotoSource.m
import "PhotoSource.h"
#implementation PhotoSource
#synthesize title = _title;
- (void)fakeLoadReady {
_fakeLoadTimer = nil;
if (_type & PhotoSourceLoadError) {
[_delegates makeObjectsPerformSelector: #selector(model:didFailLoadWithError:)
withObject: self
withObject: nil];
} else {
NSMutableArray* newPhotos = [NSMutableArray array];
for (int i = 0; i < _photos.count; ++i) {
id<TTPhoto> photo = [_photos objectAtIndex:i];
if ((NSNull*)photo != [NSNull null]) {
[newPhotos addObject:photo];
}
}
[newPhotos addObjectsFromArray:_tempPhotos];
TT_RELEASE_SAFELY(_tempPhotos);
[_photos release];
_photos = [newPhotos retain];
for (int i = 0; i < _photos.count; ++i) {
id<TTPhoto> photo = [_photos objectAtIndex:i];
if ((NSNull*)photo != [NSNull null]) {
photo.photoSource = self;
photo.index = i;
}
}
[_delegates makeObjectsPerformSelector:#selector(modelDidFinishLoad:) withObject:self];
}
}
- (id)initWithType:(PhotoSourceType)type title:(NSString*)title photos:(NSArray*)photos
photos2:(NSArray*)photos2 {
if (self = [super init]) {
_type = type;
_title = [title copy];
_photos = photos2 ? [photos mutableCopy] : [[NSMutableArray alloc] init];
_tempPhotos = photos2 ? [photos2 retain] : [photos retain];
_fakeLoadTimer = nil;
for (int i = 0; i < _photos.count; ++i) {
id<TTPhoto> photo = [_photos objectAtIndex:i];
if ((NSNull*)photo != [NSNull null]) {
photo.photoSource = self;
photo.index = i;
}
}
if (!(_type & PhotoSourceDelayed || photos2)) {
[self performSelector:#selector(fakeLoadReady)];
}
}
return self;
}
- (id)init {
return [self initWithType:PhotoSourceNormal title:nil photos:nil photos2:nil];
}
- (void)dealloc {
[_fakeLoadTimer invalidate];
TT_RELEASE_SAFELY(_photos);
TT_RELEASE_SAFELY(_tempPhotos);
TT_RELEASE_SAFELY(_title);
[super dealloc];
}
- (BOOL)isLoading {
return !!_fakeLoadTimer;
}
- (BOOL)isLoaded {
return !!_photos;
}
- (void)load:(TTURLRequestCachePolicy)cachePolicy more:(BOOL)more {
if (cachePolicy & TTURLRequestCachePolicyNetwork) {
[_delegates makeObjectsPerformSelector:#selector(modelDidStartLoad:) withObject:self];
TT_RELEASE_SAFELY(_photos);
_fakeLoadTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self
selector:#selector(fakeLoadReady) userInfo:nil repeats:NO];
}
}
- (void)cancel {
[_fakeLoadTimer invalidate];
_fakeLoadTimer = nil;
}
- (NSInteger)numberOfPhotos {
if (_tempPhotos) {
return _photos.count + (_type & PhotoSourceVariableCount ? 0 : _tempPhotos.count);
} else {
return _photos.count;
}
}
- (NSInteger)maxPhotoIndex {
return _photos.count-1;
}
- (id<TTPhoto>)photoAtIndex:(NSInteger)photoIndex {
if (photoIndex < _photos.count) {
id photo = [_photos objectAtIndex:photoIndex];
if (photo == [NSNull null]) {
return nil;
} else {
return photo;
}
} else {
return nil;
}
}
#end
Photo.h
#import <Three20/Three20.h>
#interface Photo : NSObject <TTPhoto> {
id<TTPhotoSource> _photoSource;
NSString* _thumbURL;
NSString* _smallURL;
NSString* _URL;
CGSize _size;
NSInteger _index;
NSString* _caption;
}
- (id)initWithURL:(NSString*)URL smallURL:(NSString*)smallURL size:(CGSize)size;
- (id)initWithURL:(NSString*)URL smallURL:(NSString*)smallURL size:(CGSize)size
caption:(NSString*)caption;
#end
Photo.m
#import "Photo.h"
#implementation Photo
#synthesize photoSource = _photoSource, size = _size, index = _index, caption = _caption;
- (id)initWithURL:(NSString*)URL smallURL:(NSString*)smallURL size:(CGSize)size {
return [self initWithURL:URL smallURL:smallURL size:size caption:nil];
}
- (id)initWithURL:(NSString*)URL smallURL:(NSString*)smallURL size:(CGSize)size
caption:(NSString*)caption {
if (self = [super init]) {
_photoSource = nil;
_URL = [URL copy];
_smallURL = [smallURL copy];
_thumbURL = [smallURL copy];
_size = size;
_caption;
_index = NSIntegerMax;
}
return self;
}
- (void)dealloc {
TT_RELEASE_SAFELY(_URL);
TT_RELEASE_SAFELY(_smallURL);
TT_RELEASE_SAFELY(_thumbURL);
TT_RELEASE_SAFELY(_caption);
[super dealloc];
}
- (void)viewDidLoad {
}
- (NSString*)URLForVersion:(TTPhotoVersion)version {
if (version == TTPhotoVersionLarge) {
return _URL;
} else if (version == TTPhotoVersionMedium) {
return _URL;
} else if (version == TTPhotoVersionSmall) {
return _smallURL;
} else if (version == TTPhotoVersionThumbnail) {
return _thumbURL;
} else {
return nil;
}
}
#end
AlbumController.h
#import <Three20/Three20.h>
#interface AlbumController : TTPhotoViewController <UIActionSheetDelegate>{
NSArray *images;
UIBarButtonItem *_clickActionItem;
UIToolbar *_toolbar;
}
#property (nonatomic, retain) NSArray *images;
#property (nonatomic, retain) UIBarButtonItem *_clickActionItem;
#property (nonatomic, retain) UIToolbar *_toolbar;
#end
AlbumController.m
#import "AlbumController.h"
#import "PhotoSource.h"
#import "Photo.h"
#implementation AlbumController
#synthesize images;
- (void)loadView {
CGRect screenFrame = [UIScreen mainScreen].bounds;
self.view = [[[UIView alloc] initWithFrame:screenFrame]
autorelease];
CGRect innerFrame = CGRectMake(0, 0,
screenFrame.size.width,
screenFrame.size.height);
_innerView = [[UIView alloc] initWithFrame:innerFrame];
_innerView.autoresizingMask = UIViewAutoresizingFlexibleWidth|
UIViewAutoresizingFlexibleHeight;
[self.view addSubview:_innerView];
_scrollView = [[TTScrollView alloc] initWithFrame:screenFrame];
_scrollView.delegate = self;
_scrollView.dataSource = self;
_scrollView.backgroundColor = [UIColor blackColor];
_scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth|
UIViewAutoresizingFlexibleHeight;
[_innerView addSubview:_scrollView];
UIBarButtonItem *_actionButton = [[UIBarButtonItem alloc] initWithImage:
TTIMAGE(#"bundle://Three20.bundle/images/imageAction.png")
style:UIBarButtonItemStylePlain target:self action:#selector
(popupActionSheet)];
_nextButton = [[UIBarButtonItem alloc] initWithImage:
TTIMAGE(#"bundle://Three20.bundle/images/nextIcon.png")
style:UIBarButtonItemStylePlain target:self action:#selector
(nextAction)];
_previousButton = [[UIBarButtonItem alloc] initWithImage:
TTIMAGE(#"bundle://Three20.bundle/images/previousIcon.png")
style:UIBarButtonItemStylePlain target:self action:#selector
(previousAction)];
UIBarButtonItem* playButton = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:
UIBarButtonSystemItemPlay target:self action:#selector
(playAction)] autorelease];
playButton.tag = 1;
UIBarItem* space = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:
UIBarButtonSystemItemFlexibleSpace target:nil action:nil]
autorelease];
_toolbar = [[UIToolbar alloc] initWithFrame:
CGRectMake(0, screenFrame.size.height - TT_ROW_HEIGHT,
screenFrame.size.width, TT_ROW_HEIGHT)];
_toolbar.barStyle = self.navigationBarStyle;
_toolbar.autoresizingMask = UIViewAutoresizingFlexibleWidth|
UIViewAutoresizingFlexibleTopMargin;
_toolbar.items = [NSArray arrayWithObjects:
_actionButton, space, _previousButton, space,
_nextButton, space, nil];
[_innerView addSubview:_toolbar];
}
//(Just to add an action sheet)
//At the bottom of that codefile -- I added:
-(void)popupActionSheet {
UIActionSheet *popupQuery = [[UIActionSheet alloc]
initWithTitle:nil
delegate:self
cancelButtonTitle:#"Cancel"
destructiveButtonTitle:nil
otherButtonTitles:#"Save Image",nil];
popupQuery.actionSheetStyle = UIActionSheetStyleBlackOpaque;
[popupQuery showInView:self.view];
[popupQuery release];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:
(int)buttonIndex {
//UIImage* image = [[TTURLCache sharedCache] imageForURL:imageURL];
if (buttonIndex==0){
UIImage* thisImage = [[TTURLCache sharedCache] imageForURL:
[_centerPhoto URLForVersion:TTPhotoVersionLarge]];
UIImageWriteToSavedPhotosAlbum(thisImage, nil, nil, nil);
//{UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"URL"
//message:[_centerPhoto URLForVersion:TTPhotoVersionLarge] delegate:self cancelButtonTitle:#"No" ,otherButtonTitles:#"Yes", nil];
//[alert show];}
}
}
-(void)createPhotos {
images = [[NSArray alloc] initWithObjects:
[[[Photo alloc] initWithURL:#"bundle://14.png" smallURL:#"bundle://14.png"
size:CGSizeMake(320, 212)] autorelease],
[[[Photo alloc] initWithURL:#"bundle://30.png" smallURL:#"bundle://30.png"
size:CGSizeMake(320, 212)] autorelease],
[[[Photo alloc] initWithURL:#"bundle://back.jpeg" smallURL:#"bundle://back.jpeg"
size:CGSizeMake(319, 317)] autorelease],
nil];
}
- (void)viewDidLoad {
//[self loadView];
[self createPhotos]; // method to set up the photos array
self.photoSource = [[PhotoSource alloc]
initWithType:PhotoSourceNormal
title:#"SexyGirl"
photos:images
photos2:nil
];
}
#end

If all you need is to save an image to the Photos album, you can use:
UIImage *myImage;
UIImageWriteToSavedPhotosAlbum(myImage,nil,nil,nil);
If this is not your problem, then I don't get it. If you don't tell us where the problem is, posting three pages worth of code is pretty useless.

Related

Possible memory leak

I know this is a very stupid question to ask but i have a view controller which has a mapview in it and some uibuttons i have done every thng to eliminate all the leaks bt still after 2-3 toggle between two controller app crashs. Below is the code for allocation and dellocation. BTW i dont get any "did recive memoru warning".. Thnx alot
.h/
#interface MapView : BaseViewController <MKMapViewDelegate,MKAnnotation> {
MKMapView *mapView;
NSMutableArray *placeName;
NSString *mid;
UISegmentedControl *segmentedControl;
IBOutlet UILabel *numberofbeeps;
NSInteger badgenumber;
}
#property (nonatomic, retain) UILabel *numberofbeeps;
#property(nonatomic, retain) NSString *mid;
#property (nonatomic, retain) IBOutlet MKMapView *mapView;
#property(nonatomic,retain) NSMutableArray *placeName;
#property (nonatomic,retain) IBOutlet UISegmentedControl *segmentedControl;
-(IBAction)refreshButtonPressed:(id)sender;
-(IBAction) segmentedControlIndexChanged;
-(IBAction)SignUpButtonPressed:(id)sender;
-(IBAction)BackButtonPressed:(id)sender;
-(IBAction)AddBeepButtonPressed:(id)sender;
-(id)initWithAnnotation:(id ) annotation;
-(IBAction)sliderChanged:(id)sender;
-(IBAction)MyAccountPageButtonPressed:(id)sender;
-(IBAction)MyBeepsButtonPressed:(id)sender;
#end
.m/
-(void)network:(WNetwork*)network didFinishLoadingWithRequest:(NSInteger)pReq data:(NSMutableDictionary*)pData
{
[self removeLoader];
switch (pReq) {
case JBJsonParser:
{
NSMutableArray *array = [NSMutableArray new];
self.placeName = array;
[array release];
self.placeName = pData;
badgenumber = [placeName count];
NSString *checkstring = [[AppHelper mDataManager] objectForKey:#"numberofbeepsnearby"];
NSInteger check = [checkstring intValue];
switch (check) {
case 0:
{
self.numberofbeeps.text =[NSString stringWithFormat:#"No beeps found nearby. Why not beep something?"];
NSLog(#"%#",checkstring);
}
break;
case 1:
{
self.numberofbeeps.text =[NSString stringWithFormat:#"%# beep found nearby! %d beeps worldwide.",checkstring,badgenumber];
NSLog(#"%#",checkstring);
}
break;
default:
{
self.numberofbeeps.text =[NSString stringWithFormat:#"%# beeps found nearby! %d beeps worldwide.",checkstring,badgenumber];
NSLog(#"%#",checkstring);
}
break;
}
if ([placeName count])
{
for (int i =0; i < [placeName count]; i++)
{
NSDictionary *dict = [placeName objectAtIndex:i];
CLLocationCoordinate2D coordinatemain;
coordinatemain.latitude = [[dict objectForKey:#"Lat"] doubleValue];
coordinatemain.longitude = [[dict objectForKey:#"long"] doubleValue];
DLog(#"id of Beeps %#", mid);
NSString *username = [NSString stringWithFormat:#"by %#",[dict objectForKey:#"username"]];
MyAnnotation *ann = [[MyAnnotation alloc] init];
ann.title = [dict objectForKey:#"beep"];
ann.subtitle = username;
ann.beepid=[dict objectForKey:#"beepid"];
ann.coordinate = coordinatemain;
ann.coordinate.latitude == [[dict objectForKey:#"Lat"] doubleValue];
ann.coordinate.longitude == [[dict objectForKey:#"long"] doubleValue];
[mapView addAnnotation:ann];
[ann release];
}
}
}
break;
default:
break;
}
}
-(IBAction) segmentedControlIndexChanged{
switch (self.segmentedControl.selectedSegmentIndex) {
case 0:
{
Screen1 *objCont = [[Screen1 alloc] initWithNibName:#"Screen1" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
break;
case 1:
{
MapView *objCont = [[MapView alloc] initWithNibName:#"MapView" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
break;
default:
break;
}
}
#pragma mark -
#pragma mark request delegates
-(void)makeAccomodationRequest
{
NSMutableDictionary *paramDic = [[NSMutableDictionary alloc] init];
[self.mWNetowrk makeRequsetWithURL:URL_Showbeepsmap type:JBJsonParser paramDictionary:paramDic delegate:self];
[paramDic autorelease];
}
-(BOOL)network:(WNetwork*)network shouldStartForRequest:(NSInteger)pReq
{
[self addLoaderWithtext:#"Loading"];
return YES;
}
-(void)network:(WNetwork*)network didFailForRequest:(NSInteger)pReq WithError:(NSString*)error
{
[AppHelper showAlert:error];
[self removeLoader];
}
-(void)initializeView
{
[self initializeOutlets];
[self makeAccomodationRequest];
}
-(void)initializeOutlets
{
}
-(IBAction)BackButtonPressed:(id)sender
{
Screen1 *objCont = [[Screen1 alloc] initWithNibName:#"Screen1" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
-(IBAction)refreshButtonPressed:(id)sender
{
MapView *objCont = [[MapView alloc] initWithNibName:#"MapView" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
-(IBAction)MyAccountPageButtonPressed:(id)sender
{
NSString *sid = [[AppHelper mDataManager] objectForKey:#"logout"];
{
NSDecimalNumber *session = [[AppHelper mDataManager] objectForKey:#"sid"];
if ([sid isEqualToString:#"logged out"]||session==NULL) {
AddPlace *objCont = [[AddPlace alloc] initWithNibName:#"AddPlace" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve ;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
else {
MyAccountPage *objCont = [[MyAccountPage alloc] initWithNibName:#"MyAccountPage" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve ;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
}
}
-(IBAction)MyBeepsButtonPressed:(id)sender
{
NSString *sid = [[AppHelper mDataManager] objectForKey:#"logout"];
NSDecimalNumber *session = [[AppHelper mDataManager] objectForKey:#"sid"];
//NSString *sessionStr = [session stringValue];
if ([sid isEqualToString:#"logged out"]||session==NULL) {
[[AppHelper mDataManager] setValue:#"MyBeeps" forKey:#"appflow"];
AddPlace *objCont = [[AddPlace alloc] initWithNibName:#"AddPlace" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve ;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
else {
MyBeeps1 *objCont = [[MyBeeps1 alloc] initWithNibName:#"MyBeeps1" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve ;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
}
-(IBAction)AddBeepButtonPressed:(id)sender
{
NSString *sid = [[AppHelper mDataManager] objectForKey:#"logout"];
NSDecimalNumber *session = [[AppHelper mDataManager] objectForKey:#"sid"];
if([sid isEqualToString:#"logged out"]||session==NULL) {
[[AppHelper mDataManager] setValue:#"Addabeep" forKey:#"appflow"];
AddPlace *objCont = [[AddPlace alloc] initWithNibName:#"AddPlace" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve ;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
else {
[[AppHelper mDataManager] setValue:#"Addabeep" forKey:#"appflow"];
Check20M *objCont = [[Check20M alloc] initWithNibName:#"Check20M" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve ;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
}
#pragma mark -
#pragma mark MKMapViewDelegate
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
if (annotation == mapView.userLocation) {
// NSLog(#"nil");
return nil; }
MKPinAnnotationView *pinView = nil;
static NSString *defaultPinID = #"com.invasivecode.pin";
pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
if ( pinView == nil )
pinView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];
pinView.pinColor = MKPinAnnotationColorGreen;
pinView.frame=CGRectMake(0, 0, 30, 30);
pinView.canShowCallout = YES;
pinView.animatesDrop = YES;
UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
MyAnnotation *temp = (MyAnnotation*)annotation;
infoButton.tag = [temp.beepid integerValue];
[infoButton addTarget:self action:#selector(showDetails:) forControlEvents:UIControlEventTouchUpInside];
pinView.rightCalloutAccessoryView = infoButton;
[defaultPinID release];
return pinView;
}
-(IBAction)showDetails:(id)sender{
UIButton *button = (UIButton*)sender ;
NSLog(#"Annotation Click");
BeepsDetail *objCont = [[BeepsDetail alloc] initWithNibName:#"BeepsDetail" bundle:nil];
objCont.mId = [NSString stringWithFormat:#"%d",button.tag];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
#pragma mark -
#pragma mark mapView delegates
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
mapView.delegate = self;
[self initializeView];
mapView.showsUserLocation = YES;
[self makeAccomodationRequest];
CLLocation *location = [[AppHelper appDelegate] mLatestLocation];
MKCoordinateRegion region;
region.center.latitude = location.coordinate.latitude;
region.center.longitude = location.coordinate.longitude;
region.span.latitudeDelta = 0.001;
// Add a little extra space on the sides
region.span.longitudeDelta = 0.001;
// Add a little extra space on the sides
region = [mapView regionThatFits:region];
[mapView setRegion:region animated:YES];
}
// Listen to change in the userLocation
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
self.mapView = nil;
self.numberofbeeps =nil;
self.mapView = nil;
self.segmentedControl = nil;
}
- (void)dealloc
{
[mapView release];
// [self.mapView removeFromSuperview];
[placeName release];
//[mid autorelease];
[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.
}
#end
The following only works on the simulator not on device...
Here is a good procedure for finding bad access errors using zombies. All the tools are built into Xcode.
First change to profiling. Click and hold one the run button.
Now choose zombies. This tool warns you just before you are about to use a deallocated object which would other wise trigger a bad access.
Now when a zombie is detected you will see something like this (minus annotatios!) using the tools you can see the object lifecycle. Double click to be taken the the code.
Hope it helps someone!
I would suggest declaring modal view controllers (objCont) as autorelease as opposed to manually releasing them.

AlAssetsLibrary issue, code works in 4.3 but not 5.0

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."

I am unable to copy my NSMutable array to appDelegate_iPhone array(Universal app)

Actually I have parsed an XML and store URL's of images as an NSMutableArray object, but I want this array to be used in another ViewController (to give to UIImage in UIImageView to show Images at runtime), so I am trying to copy that Mutable array to myAppDelegate_iPhone's NSMutableArray. And I want to again copy that Appdelegate's array to my next or other ViewControllers NSMutableArray.
so can anyone help me out pleaseeeeee? Here is my code :-
code:-
#class FirstViewController;
#interface AppDelegate_iPhone : NSObject <UIApplicationDelegate> {
UIWindow *window;
FirstViewController *viewController;
NSMutableArray *logoArray;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) NSMutableArray *logoArray;
#end
#import "AppDelegate_iPhone.h"
#import "FirstViewController.h"
#import "ParsingViewController.h"
#implementation AppDelegate_iPhone
#synthesize window,logoArray;
#pragma mark -
#pragma mark Application lifecycle
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
viewController = [[FirstViewController alloc]initWithNibName:#"FirstViewController" bundle:nil];
viewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
NSURL *url = [[NSURL alloc] initWithString:#"http://litofinter.es.milfoil.arvixe.com/displayxml1.aspx"];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
//Initialize the delegate.
ParsingViewController *parser = [[ParsingViewController alloc] init];
//Set delegate
[xmlParser setDelegate:parser];
//Start parsing the XML file.
BOOL success = [xmlParser parse];
if(success)
NSLog(#"No Errors");
else
NSLog(#"Error Error Error!!!");
logoArray = [[NSMutableArray alloc]init];
[self.window addSubview:viewController.view];
[self.window makeKeyAndVisible];
return YES;
}
// dealloc done
#end
#class Litofinter,AppDelegate_iPhone;
#interface ParsingViewController : NSObject<NSXMLParserDelegate> {
NSString *myString;
NSMutableArray *myMutableArray;
Litofinter *obj;
NSString *currentElement;
AppDelegate_iPhone *appDelegate;
}
#import "ParsingViewController.h"
#import "Litofinter.h"
#import "AppDelegate_iPhone.h"
#implementation ParsingViewController
#synthesize myMutableArray, myString;
-(id)init{
if(self == [super init]){
myMutableArray = [[NSMutableArray alloc] init];
}
return self;
}
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
//myMutableArray = [[NSMutableArray alloc]init];
}
// Parsing done here
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
appDelegate = (AppDelegate_iPhone *)[[UIApplication sharedApplication] delegate];
//UIApplication *app = [UIApplication sharedApplication];
//appDelegate=app.delegate;
appDelegate.logoArray = [[NSMutableArray alloc]initWithArray:myMutableArray];
NSLog(#"appDelegate.logoArray count %d",[appDelegate.logoArray count]);
for (Litofinter *lito in appDelegate.logoArray) {
NSLog(#"Array Elements :----- %#",lito.cLogo);
}
}
#end
#import <UIKit/UIKit.h>
#class AppDelegate_iPhone,Litofinter,ParsingViewController;
#interface FirstViewController : UIViewController {
NSMutableArray *array;
//Litofinter *lito;
NSString *logoString;
AppDelegate_iPhone *appDelegate;
ParsingViewController *obj;
}
#end
#import "FirstViewController.h"
#import "AppDelegate_iPhone.h"
#import "Litofinter.h"
#import "ParsingViewController.h"
#implementation FirstViewController
-(id)init{
if(self == [super init]){
obj = [[ParsingViewController alloc] init];
array = [[NSArray alloc] initWithArray: obj.myMutableArray];
}
return self;
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
int x=5,y=10;
appDelegate = (AppDelegate_iPhone *)[[UIApplication sharedApplication] delegate];
// UIApplication *app = [UIApplication sharedApplication];
// appDelegate=app.delegate;
NSLog(#"delegate Array ====== %d",[appDelegate.logoArray count]);
NSLog(#"New Array ====== %d",[obj.myMutableArray count]);
/*
array = [[NSMutableArray alloc]initWithArray:appDelegate.logoArray];
NSLog(#"array at 0 ===== %#",[array objectAtIndex:0]);
for (Litofinter *lito1 in obj.myMutableArray) {
NSLog(#"Array Elements in Lito1 are :------------- %#",lito1.cLogo);
}
for (Litofinter *lito2 in array) {
NSLog(#"Array Elements in Lito1 are :------------- %#",lito2.cLogo);
}
*/
for (Litofinter *lito in obj.myMutableArray) {
//for (int i=0; i<[appDelegate.logoArray count]; i++) {
// lito.cLogo = [array objectAtIndex:i];
NSLog(#"%#",lito.cLogo);
UIImage *imageFromUrl = [UIImage imageWithContentsOfFile:[NSURL fileURLWithPath:lito.cLogo]];
UIImageView *imgView = [[UIImageView alloc] initWithImage:imageFromUrl];
[imgView setFrame:CGRectMake(x, y, 196, 90)];
[self.view addSubview:imgView];
UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(onTapImage)];
[imgView addGestureRecognizer:tgr];
// [tgr release];
//Do the rest of your operations here, don't forget to release the UIImageView
x = x + 200;
}
}
-(void)onTapImage
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Message from mAc" message:#"Trail" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok",nil];
[alert show];
}
- (void)dealloc {
[super dealloc];
}
#end
You can use this.
UIImage *imageFromUrl = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:lito.cLogo]]];

Memory leaks in NSMutableDictionary

My coding contains a memory leak, and somehow I can't find the leak.
Leaks points me in the direction of the way I create "ReportDetailItems"
e.g. areaContainer = [[[ReportDetailItem alloc] init] autorelease];
I've been looking at this for hours and I am at a total loss, the objects reported leaking are "ReportDetailItem", and the NSMutableDictionary contained in those objects.
Please advice.
------[ReportDetailItem.h
#interface ReportDetailItem : NSObject
{
NSNumber *total;
NSMutableDictionary *items;
}
#property (nonatomic, retain) NSNumber *total;
#property (nonatomic, retain) NSMutableDictionary *items;
- (NSString *)description;
#end
------[ReportDetailItem.m
#synthesize items, total;
- (id)init {
if (self = [super init]) {
self.items = [NSMutableDictionary dictionaryWithCapacity:0];
DLog("Alloc: %d", [items retainCount]);
}
return self;
}
- (NSString *)description {
return #"ReportDetailItem";
}
- (void)release {
[super release];
}
- (void)dealloc {
[self.items release];
[self.total release];
items = nil;
total = nil;
[super dealloc];
}
#end
------[Leaking code
NSError *error;
NSArray *data = [self.managedObjectContext executeFetchRequest:request error:&error];
if (data == nil || [data count] == 0) {
DLog(#"No data.")
} else {
for (int i=0; i < [data count]; i++) {
TaskEntity *task = [data objectAtIndex:i];
NSString *areaKey = task.activity.project.area.title.text;
NSString *projectKey = task.activity.project.title.text;
NSString *activityKey = task.activity.title.text;
ReportDetailItem *areaContainer;
if (![dataSource objectForKey:areaKey]) {
areaContainer = [[[ReportDetailItem alloc] init] autorelease];
} else {
areaContainer = [dataSource objectForKey:areaKey];
}
areaContainer.total = [NSNumber numberWithInt:([task.seconds intValue] + [areaContainer.total intValue])];
[dataSource setObject:areaContainer forKey:areaKey];
ReportDetailItem *projectContainer;
if (![areaContainer.items objectForKey:projectKey]) {
projectContainer = [[[ReportDetailItem alloc] init] autorelease];
} else {
projectContainer = [areaContainer.items objectForKey:projectKey];
}
projectContainer.total = [NSNumber numberWithInt:([task.seconds intValue] + [projectContainer.total intValue])];
[areaContainer.items setObject:projectContainer forKey:projectKey];
ReportDetailItem *activityContainer;
if (![projectContainer.items objectForKey:activityKey]) {
activityContainer = [[[ReportDetailItem alloc] init] autorelease];
} else {
activityContainer = [projectContainer.items objectForKey:activityKey];
}
activityContainer.total = [NSNumber numberWithInt:([task.seconds intValue] + [activityContainer.total intValue])];
[projectContainer.items setObject:activityContainer forKey:activityKey];
}
}
I found it, the leak was located in the way I allocated the "dataSource"
---[Leak
- (void)viewDidLoad {
[super viewDidLoad];
self.dataSource = [[NSMutableDictionary alloc] init];
[self fetchData];
}
---[No leak
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
self.dataSource = dict;
[dict release];
[self fetchData];
}
I'm pretty skeptic about the two ways u assign pointers to the ReportDetailItem. Why are you trying to autorelease the object in the first place? If not try this
ReportDetailItem *projectContainer;
if (![areaContainer.items objectForKey:projectKey]) {
projectContainer = [[ReportDetailItem alloc] init];
} else {
projectContainer = [[areaContainer.items objectForKey:projectKey] retain];
}
projectContainer.total = [NSNumber numberWithInt:([task.seconds intValue] + [projectContainer.total intValue])];
[areaContainer.items setObject:projectContainer forKey:projectKey];
if(projectContainer) {
[projectContainer release];
projectContainer = nil;
}

how can i integrate ticker in iphone application

i want to run my view based window application with ticker.i have code for ticker but it is in cocoa..
so how can i integrate cocoa application in my project.?
this is TickerView.h file
#import <Cocoa/Cocoa.h>
#interface TickerView : NSTextView {
#private
NSTimer *mTimer;
double mOffset;
}
- (NSString *)stringValue;
- (void)setStringValue:(NSString *)stringValue;
- (void)appendString:(NSString *)s;
- (IBAction)startAnimation:(id)sender;
- (IBAction)stopAnimation:(id)sender;
#end
This is TickerView.m file
#import "TickerView.h"
#implementation TickerView
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self setEditable:NO];
NSTextContainer *container = [self textContainer];
[container setWidthTracksTextView:NO];
[container setContainerSize:NSMakeSize(99999., frame.size.height)];
}
return self;
}
- (void)dealloc {
[self stopAnimation:self];
[super dealloc];
}
- (void)drawRect:(NSRect)rect {
[super drawRect:rect];
}
- (NSString *)stringValue {
return [[self textStorage] string];
}
- (NSDictionary *)standardAttributes {
return [NSDictionary dictionaryWithObjectsAndKeys:
[NSFont fontWithName:#"Helvetica" size:([self frame].size.height * 0.8)], NSFontAttributeName,
[NSColor redColor], NSForegroundColorAttributeName,
nil];
}
- (void)setStringValue:(NSString *)s {
NSRange fullRange = NSMakeRange(0, [[self textStorage] length]);
NSAttributedString *sa = [[[NSAttributedString alloc]initWithString:s attributes:[self standardAttributes]] autorelease];
[[self textStorage] replaceCharactersInRange:fullRange withAttributedString:sa];
}
- (void)appendString:(NSString *)s {
NSRange endRange = NSMakeRange([[self textStorage] length], 0);
NSAttributedString *sa = [[[NSAttributedString alloc]initWithString:s attributes:[self standardAttributes]] autorelease];
[[self textStorage] replaceCharactersInRange:endRange withAttributedString:sa];
}
- (IBAction)startAnimation:(id)sender {
if (nil == mTimer) {
mTimer = [NSTimer scheduledTimerWithTimeInterval:1./60. target:self selector:#selector(step:) userInfo:nil repeats:YES];
}
}
- (IBAction)stopAnimation:(id)sender {
if (mTimer) {
[mTimer invalidate];
[mTimer release];
mTimer = nil;
}
}
- (void)step:(NSTimer *)timer {
mOffset -= 2; // pixels per tick
[self setTextContainerInset:NSMakeSize(mOffset, 0)];
[self setNeedsDisplay:YES];
}
#end
You can't just drop it in (as far as I know).
I'd do it by changing your inheritance from NSTextView to UILabel and reading the docs for that. then just work through the code bit by bit until it works ;)