Memory Management on NSMutableArray - memory-leaks

I read some materials about this then I tried to wrote a simple
app but got confused, here is the sample (using cocos2d template):
MySpriteObject class:
#import <Foundation/Foundation.h>
#import "cocos2d.h"
#interface MySpriteObject : CCNode {
CCSprite *mySprite;
NSString *spriteInfo;
}
#property(nonatomic,retain) CCSprite *mySprite;
#property(nonatomic,retain) NSString *spriteInfo;
#end
#import "MySpriteObject.h"
#implementation MySpriteObject
#synthesize mySprite;
#synthesize spriteInfo;
-(id) init
{
NSLog(#"MySpriteObject init");
if ((self = [super init])) {
self.mySprite = [CCSprite spriteWithFile:#"Icon.png"];
self.spriteInfo = [[[NSString alloc] initWithFormat:#"sprite info"] autorelease];
}
return (self);
}
-(void)dealloc
{
NSLog(#"MySpriteObject dealloc");
[self.spriteInfo release];
[super dealloc];
}
#end
MyObjectManager class:
#import "cocos2d.h"
#import "MySpriteObject.h"
#class MySpriteObject;
#interface MyObjectManager : CCNode {
}
+(MyObjectManager *)sharedMyObjectManager;
-(NSMutableArray *)func1;
-(NSMutableArray *)func2;
#end
#import "MyObjectManager.h"
#import "MySpriteObject.h"
#implementation MyObjectManager
static MyObjectManager *_sharedMyObjectManager = nil;
+(MyObjectManager *)sharedMyObjectManager
{
NSLog(#"MyObjectManager sharedMyObjectManager");
if (!_sharedMyObjectManager) {
if( [ [MyObjectManager class] isEqual:[self class]] )
_sharedMyObjectManager = [[MyObjectManager alloc] init];
else
_sharedMyObjectManager = [[self alloc] init];
}
return _sharedMyObjectManager;
}
-(id)init
{
NSLog(#"MyObjectManager init");
if( (self = [super init]) ) {
}
return self;
}
-(void)dealloc
{
NSLog(#"MyObjectManager dealloc");
[super dealloc];
}
-(NSMutableArray *)func1
{
NSMutableArray *array1 = [[NSMutableArray alloc] init];
array1 = [self func2];
return array1;
}
-(NSMutableArray *)func2;
{
NSMutableArray *array2 = [[NSMutableArray alloc] init];
for (int i = 0; i < 3; i++) {
MySpriteObject *mySpriteObject = [[MySpriteObject alloc] init];
[array2 addObject:mySpriteObject];
//[mySpriteObject release];
}
return array2;
}
#end
And in the "HelloWorldScene.m" init method:
-(id) init
{
if( (self=[super init] )) {
NSMutableArray *array = [[NSMutableArray alloc] init];
array = [[MyObjectManager sharedMyObjectManager] func1];
for (int i = 0; i < array.count; i++) {
MySpriteObject *s = [[MySpriteObject alloc] init];
s = [array objectAtIndex:i];
NSLog(#"%#", s.spriteInfo);
[s release];
}
[array release];
}
return self;
}
The code posted above works fine (at least no crash), but I think there is
memory leak out there.
At first, I had the fun1 fun2 method return the array like this:
return [array1 autorelease];
return [array2 autorelease];
And released the SpriteObject in the func2 methoed as you can see the commented line.
But the app crashed.
Then I uncommented the SpriteObject release line but it still crashed.
Then I deleted the two autorelease in the return statement and it worked
fine.
Can somebody give something suggestion according to the code above???
Thanks in advance.

Oh boy, there are multiple problems. At first remember to release everything you called "alloc, new, retain, copy" upon. See Objective C release, autorelease, and data types and Release, Dealloc, and the Self reference
The basic problem here is, that you are overwriting previously created variables. For example:
NSMutableArray *array = [[NSMutableArray alloc] init];
array = ... ;
[array release];
Therefore you create a memory leak and get double release trouble. See obj-c NSString and alloc / retain / release for how to do it right.

Related

CoreDataTableViewController does not reload on return from segue

I have several CoreDataTableViewControllers that utilize the helper class from Paul Hegarty's course. Everyone of them works except this one, and I cannot see a difference.
When the table first comes up, it is correctly populated and the segue executes properly when a cell is selected. However when I hit the back button, the table displays (null), (null) everywhere.
I have tried every variant of calling [self useDocument] that I can think of, still to no avail. Any thoughts? Thanks in advance.
//
// TeamTableViewController.m
//
#import "TeamTableViewController.h"
#import "iTrackAppDelegate.h"
#import "CoreDataTableViewController.h"
#import "SchoolRecords.h"
#import "ScheduleViewController.h"
#interface TeamTableViewController ()
#property NSInteger toggle;
#end
#implementation TeamTableViewController
#synthesize iTrackContext = _iTrackContext;
#synthesize schoolSelected = _schoolSelected;
-(void) setSchoolSelected:(SchoolRecords *)schoolSelected
{
_schoolSelected = schoolSelected;
}
-(void) setITrackContext:(NSManagedObjectContext *)iTrackContext
{
if(_iTrackContext != iTrackContext){
if (!iTrackContext) {
MyCoreDataHandler* cdh =
[(iTrackAppDelegate *) [[UIApplication sharedApplication] delegate] cdh];
_iTrackContext = cdh.context;
} else {
_iTrackContext = iTrackContext;
}
}
[self useDocument];
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)setupFetchedResultsController // attaches an NSFetchRequest to this UITableViewController
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"SchoolRecords"];
// no predicate because we want ALL the Athletes
request.sortDescriptors = [NSArray arrayWithObjects:
[NSSortDescriptor sortDescriptorWithKey:#"schoolName" ascending:YES],
nil];
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.iTrackContext
sectionNameKeyPath:nil
cacheName:nil];
__block NSInteger myCount;
int64_t delayInSeconds = 5.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[self.iTrackContext performBlock:^(void){NSError* requestError = nil;
myCount = [self.iTrackContext countForFetchRequest:request error:&requestError];
NSLog(#"In %# and count of iTrackContext = %lu", NSStringFromClass([self class]),(unsigned long)myCount);
}];
if (!myCount || myCount == 0) {
[self displayAlertBoxWithTitle:#"No Teams" message:#"Have you added athletes yet? \nPlease go to Add Athletes" cancelButton:#"Okay"];
}
});
}
- (void)useDocument
{
if (self.iTrackContext) {
[self setupFetchedResultsController];
} else {
NSString* errorText = #"A problem arose opening the search results database of Athletes.";
[self displayAlertBoxWithTitle:#"File Error" message:errorText cancelButton:#"Okay"];
}
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
if (!self.iTrackContext) {
MyCoreDataHandler* cdh =
[(iTrackAppDelegate *) [[UIApplication sharedApplication] delegate] cdh];
[self setITrackContext:cdh.context];
} else {
NSLog(#"In %# of %#. Getting ready to call useDocument",NSStringFromSelector(_cmd), self.class);
[self useDocument];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// If divide into sections use line below otherwise return 1.
// return [[self.fetchedResultsController sections] count];
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Do not really need this with only one section, but makes code usable if add sections later.
return [[[self.fetchedResultsController sections] objectAtIndex:section] numberOfObjects];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"teamInformation";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
SchoolRecords *schoolResults = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSString* titleText = schoolResults.schoolName;
cell.textLabel.text = titleText;
cell.detailTextLabel.text = [NSMutableString stringWithFormat:#"%#, %#", schoolResults.schoolCity, schoolResults.schoolState];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
# pragma navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
[self setSchoolSelected:[self.fetchedResultsController objectAtIndexPath:indexPath]];
// be somewhat generic here (slightly advanced usage)
// we'll segue to ANY view controller that has a photographer #property
if ([segue.identifier isEqualToString:#"scheduleDetailSegue"]) {
// use performSelector:withObject: to send without compiler checking
// (which is acceptable here because we used introspection to be sure this is okay)
NSLog(#"Preparing to passing school with schoolID = %#", self.schoolSelected.schoolID);
[segue.destinationViewController convenienceMethodForSettingSchool:self.schoolSelected];
}
}
- (void) displayAlertBoxWithTitle:(NSString*)title message:(NSString*) myMessage cancelButton:(NSString*) cancelText
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:myMessage
delegate:nil
cancelButtonTitle:cancelText
otherButtonTitles:nil];
[alert show];
}
#end
Well, I am not certain what the problem was. I ended up deleting the "offending" TableViewControllers in StoryBoard and recreated them. That did the trick. In retrospect, I wonder if I did not specify the wrong type of segue from my tabViewController. But I deleted it before I thought of that possibility.

Core-Data: Very confused by the implementation of multiple NSManagedObjects and an NSFetchedResultsController in a multithreading iOS app

I have a routine that fetches RSS entries in the background and insert these in my NSManagedObjectContext if not already there.
My problem is that this object doesn't find duplicates or crashes, depending on which NSManagedObjectContext I use... Help me, please.
Here's the simplified .h
#interface AsyncFetchEngine : NSObject <NSXMLParserDelegate,NSFetchedResultsControllerDelegate>
#property (strong, nonatomic) dispatch_queue_t rssParserQueue;
#property (strong, nonatomic) NSMutableArray *uRLsToFetch;
#property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (strong, nonatomic) NSManagedObjectContext *childManagedObjectContext;
#property (strong, nonatomic) NSFetchedResultsController *fetchedResultsController;
- (Boolean) isAlreadyInTheFetchQueue:(Feed *)feed;
- (void) fetchPosts:(Feed *)feed;
- (void) createPostInFeed:(Feed*)feed withTitle:(NSString *)title withContent:(NSString *)content withURL:(NSString *)url withDate:(NSDate *)date;
Now here's the init method:
Note if I set the _childManagedObjectContext's parent here, the program crashes.
-(AsyncFetchEngine *)init
{
_rssParserQueue = dispatch_queue_create("com.example.MyQueue", NULL);
_uRLsToFetch = [[NSMutableArray alloc] initWithCapacity:32];
_childManagedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[_childManagedObjectContext setPersistentStoreCoordinator:[_managedObjectContext persistentStoreCoordinator]];
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self
selector:#selector(contextDidSave:)
name:NSManagedObjectContextDidSaveNotification
object:_childManagedObjectContext];
return self;
}
- (void)contextDidSave:(NSNotification*)notification
{
void (^mergeChanges) (void) = ^ {
[_managedObjectContext mergeChangesFromContextDidSaveNotification:notification];
};
if ([NSThread isMainThread]) {
mergeChanges();
} else {
dispatch_sync(dispatch_get_main_queue(), mergeChanges);
}
}
Fetch method:
Note: not sure which MOC to use to determine localFeed, _managedObjectContext crashes the app.
- (void) fetchPosts:(Feed *)feed
{
if (!_childManagedObjectContext.parentContext) {
[_childManagedObjectContext setParentContext:self.managedObjectContext];
}
if ([self isAlreadyInTheFetchQueue:feed]) {
NSLog(#"AsyncFetchEngine::fetchPosts> \"%#\" is already in the fetch queue", feed.name);
return;
}
[_uRLsToFetch addObject:feed];
NSURL *url=[NSURL URLWithString:feed.rss];
NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url];
if (![NSURLConnection canHandleRequest:req]) {
return;
}
Feed *localFeed = ((Feed *)[_childManagedObjectContext existingObjectWithID:[feed objectID] error:nil]);
dispatch_async(_rssParserQueue, ^{
NSLog(#"AsyncFetchEngine::fetchPosts> Opening %#", feed.rss);
[RSSParser parseRSSFeedForRequest:req success:^(NSArray *feedItems)
{
for(RSSItem *i in feedItems)
{
[self createPostInFeed:localFeed withTitle:i.title withContent:(i.content?i.content:i.itemDescription) withURL:[i.link absoluteString] withDate:(i.pubDate?i.pubDate:[NSDate date])];
}
NSLog(#"AsyncFetchEngine::fetchPosts> Found %d items", [feedItems count]);
[_uRLsToFetch removeObject:feed];
}
failure:^(NSError *error)
{
NSLog(#"AsyncFetchEngine::fetchPosts> RSSParser lost it: %#", [error localizedDescription]);
}];
});
}
- (Boolean) isAlreadyInTheFetchQueue:(Feed *)feed
{
Feed *f=nil;
for (f in _uRLsToFetch) {
if ([f isEqual:feed]){
return YES;
}
}
return NO;
}
NSFecthedResultsController, do I need it that way?
- (NSFetchedResultsController *)fetchedResultsController
{
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
// Note: I originally tried to use the main MOC here, but it also used to crash the app.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Post" inManagedObjectContext:_childManagedObjectContext];
[fetchRequest setEntity:entity];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"date" ascending:NO];
NSArray *sortDescriptors = #[sortDescriptor];
[fetchRequest setSortDescriptors:sortDescriptors];
/* NSPredicate *predicate =[NSPredicate predicateWithFormat:#"feed.rss LIKE '%#'", _detailItem.rss];
[fetchRequest setPredicate:predicate]; */
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
aFetchedResultsController.delegate = self;
_fetchedResultsController = aFetchedResultsController;
return _fetchedResultsController;
}
It usually crashes somewhere in this method, according to the dump stack.
If it doesn't crash, I have my post added to a (null) Category...
- (void)createPostInFeed:(Feed*)feed withTitle:(NSString *)title withContent:(NSString *)content withURL:(NSString *)url withDate:(NSDate *)date
{
[_childManagedObjectContext performBlockAndWait:^{
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
NSLog(#"Error in refetch: %#",[error localizedDescription]);
abort();
}
}];
NSLog(#"AsyncFetchEngine.h: Searching similar posts among %d", [[self.fetchedResultsController fetchedObjects] count]);
Boolean found=NO;
NSPredicate *predicate=[NSPredicate predicateWithFormat:#"title == %# AND url == %# AND feed == %#", title, url, feed];
NSArray *similarPosts = [_fetchedResultsController.fetchedObjects filteredArrayUsingPredicate:predicate];
if ([similarPosts count] > 0)
{
NSLog(#"\n\n\n\t\tAsyncFetchEngine::fetchPosts> Skipping %# (%#)", title, url);
} else {
NSLog(#"\n\n\n\t\tAsyncFetchEngine::fetchPosts> Putting new post in %#", feed.name);
NSEntityDescription *postEntityDescription = [NSEntityDescription entityForName:#"Post"
inManagedObjectContext:_childManagedObjectContext];
[_childManagedObjectContext performBlock:^{
Post *initPost = (Post *)[[NSManagedObject alloc]
initWithEntity:postEntityDescription
insertIntoManagedObjectContext:_childManagedObjectContext];
initPost.title = title;
initPost.url = url;
initPost.excerpt = content;
initPost.date = date;
initPost.read = nil;
initPost.feed = feed;
NSError *error;
if (![_childManagedObjectContext save:&error])
{
NSLog(#"[createPost] Error saving context: %#", error);
}
NSLog(#"Created: %# (%#)", title, url);
//[[NSNotificationCenter defaultCenter] postNotificationName:#"NewPostAdded" object:self];
}];
}
}
So, my questions are:
When I have multiple MOCs, do I fetch from the main and write to a child?
How should I respectivelly use these above?
Thanks!
Answering my own question for the sake of eventually helping another newbie.
Check NSOperationQueue with Coredata.
There's a very good example here.

Singleton class for displaying iAds for iPhone

I have written a Singleton Class for managing iAds.The iAds pop up after 5 seconds of the user inactivity. The idleTimerExceeded call generate a notification to show the iAd. This code works fine for my requirements but since I am new to iOS development, my application sometimes hangs unexpectedly after integrating this code. This code results in lots of warnings etc. I would like to optimize my code in terms of memory and performance.
I would be very thankful for your kind suggestions and reviews.
Below is my code:
iAdSingleton.h
#import <Foundation/Foundation.h>
#import "AppDelegate.h"
#import "iAd/iAd.h"
#interface iAdSingleton : UIViewController<ADBannerViewDelegate> {
ADBannerView *adView;
UIViewController *displayVC;
NSTimer *idleTimer;
BOOL isItFirstTime;
}
#property (nonatomic, retain) ADBannerView *adView;
#property (nonatomic, retain) UIViewController *displayVC;
#property (nonatomic) BOOL isItFirstTime;
+ (id) shareAdSingleton;
- (void) resetIdleTimer;
- (void) idleTimerExceeded;
#end
iAdSingleton.m
#import "iAdSingleton.h"
#implementation iAdSingleton
static iAdSingleton* _sharedAdSingleton = nil;
BOOL bannerVisible = NO;
BOOL controlAccessBannerVisibility = NO;
#synthesize adView, displayVC;
#synthesize isItFirstTime;
#define kMaxIdleTimeSeconds 5.0
+(id)sharedAdSingleton
{
#synchronized(self)
{
if(!_sharedAdSingleton)
_sharedAdSingleton = [[self alloc] init];
return _sharedAdSingleton;
}
return nil;
}
+(id)alloc
{
#synchronized([iAdSingleton class])
{
NSAssert(_sharedAdSingleton == nil, #"Attempted to allocate a second instance of a singleton.");
_sharedAdSingleton = [super alloc];
return _sharedAdSingleton;
}
return nil;
}
-(id)init
{
self = [super init];
if (self != nil) {
/* Initialize The Parameters Over Here */
//adView = [[ADBannerView alloc] initWithFrame:CGRectMake(0, 480, 0, 0)];
adView = [[ADBannerView alloc] init];
adView.currentContentSizeIdentifier = ADBannerContentSizeIdentifierPortrait;
self.adView.delegate=self;
[self resetIdleTimer];
}
return self;
}
-(void)dealloc
{
displayVC = nil;
if (adView) {
[adView removeFromSuperview]; //Remove ad view from superview
[adView setDelegate:nil];
adView = nil;
}
[super dealloc];
}
-(UIViewController *)viewControllerForPresentingModalView
{
return displayVC;
}
- (void)bannerViewDidLoadAd:(ADBannerView *)banner
{
banner.hidden = NO;
if(!bannerVisible){
NSLog(#"Banner Changes 1 - Purpose: Visibility");
// [UIView beginAnimations:#"bannerAppear" context:NULL];
// banner.frame = CGRectOffset(banner.frame, 0, -100);
// [UIView commitAnimations];
bannerVisible = YES;
controlAccessBannerVisibility = YES;
}
}
- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{
//NSLog(#"Unable to receive Ad.");
NSLog(#"Banner Changes 2 - Purpose: Unable to Receive Ad.");
banner.hidden = YES;
if(bannerVisible){
[UIView beginAnimations:#"bannerDisappear" context:NULL];
banner.frame = CGRectOffset(banner.frame, 0, 100);
[UIView commitAnimations];
bannerVisible = NO;
}
}
- (BOOL) bannerViewActionShouldBegin:(ADBannerView *)banner willLeaveApplication:(BOOL)willLeave
{
NSLog(#"Pause anything necessary");
return YES;
}
- (void) bannerViewActionDidFinish:(ADBannerView *)banner
{
NSLog(#"We now resume to normal operations");
}
- (void)resetIdleTimer {
if (!idleTimer) {
idleTimer = [[NSTimer scheduledTimerWithTimeInterval:kMaxIdleTimeSeconds
target:self
selector:#selector(idleTimerExceeded)
userInfo:nil
repeats:NO] retain];
}
else {
if (fabs([idleTimer.fireDate timeIntervalSinceNow]) < kMaxIdleTimeSeconds-1.0) {
[idleTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:kMaxIdleTimeSeconds]];
/*
Notification: HideAd
*/
NSLog(#"Notification Generated For HideAd");
[[NSNotificationCenter defaultCenter] postNotificationName:#"HideAdBanner" object:nil userInfo:nil];
}
}
}
- (void)idleTimerExceeded {
AppDelegate *appDel = (AppDelegate *)[[UIApplication sharedApplication] delegate];
if (appDel.adVisible == NO) {
NSLog(#"Notification Generated For ShowAd");
/*
Notification: ShowAd
*/
if (controlAccessBannerVisibility == YES) {
[[NSNotificationCenter defaultCenter] postNotificationName:#"ShowAdBanner" object:nil userInfo:nil];
}
}
}
#end
This is what you need. This code is thread safe as well as will not have any memory issue and warnings.
+ (iAdSingleton *) sharedInstance
{
static dispatch_once_t onceToken;
static iAdSingleton * __sharedInstance = nil;
dispatch_once(&onceToken, ^{
__sharedInstance = [[self alloc] init];
});
return __sharedInstance;
}

Appending NSMutableStrings - Exepected "." before "." token error

I'm not sure what I'm doing wrong. I'm thinking its because the NSMutableArray's *name and *field are declared in a different file.
#import <Foundation/Foundation.h>
#interface xmlToUrl : NSObject {
NSString *base_url;
NSMutableArray *field;
NSMutableArray *name;
}
#property(nonatomic,retain)NSString *base_url;
#property(nonatomic, retain)NSMutableArray *field;
#property(nonatomic, retain)NSMutableArray *name;
#end
and
#import "xmlToUrl.h"
#implementation xmlToUrl
#synthesize base_url;
#synthesize field;
#synthesize name;
-(id) init
{
self = [super init];
if (self) {
field = [[NSMutableArray alloc] init];
name = [[NSMutableArray alloc] init];
}
return self;
}
-(void)dealloc
{
[base_url release];
[field release];
[name release];
[super dealloc];
}
#end
The NSMutableArrays are filled in the ViewController class:
//nodeContent is just a NSMutableString being added to the *name and *field NSMutableArrays
if([ending isEqualToString:#"name"]){
if(![nodeContent isEqualToString:#""])
{[xmlToUrlObject.name addObject:nodeContent];}
}
else if([ending isEqualToString:#"field"]){
if(![nodeContent isEqualToString:#""])
{[xmlToUrlObject.field addObject:nodeContent];}
Error = Expected '.' before '.' token. (on the first line of the code below)
What I want for output: *url string contains base_url, urlPart2, and urlPart3 all joined in order.
ex:
base_url = #"www."
urlPart2 = #"mywebsite"
urlPart3 = #".com"
url = #"www.mywebsite.com"
//xmlToUrl is an instance of its own class (.m file) It contains the *name and *field NSMutableArray
//xmlToUrl.h is inherited in this file
NSMutableString *urlPart2 = [xmlToUrl.name objectAtIndex: 0];
[xmlToUrl.name removeObjectAtIndex:0];
NSMutableString *url = [xmlToUrl.base_url stringByAppendingString:urlPart2];
if([xmlToUrl.field count] != 0)
{NSMutableString *urlPart3 = [xmlToUrl.field objectAtIndex: 0];
[xmlToUrl.field removeObjectAtIndex:0}
url = [url stringByAppendingString:urlPart3];
[urlPart2 release];
[urlPart3 release];
You are trying to access a property on a class, and not on the instance:
#interface xmlToUrl : NSObject {
and
NSMutableString *urlPart2 = [xmlToUrl.name objectAtIndex: 0];
You can only access the property on an instance of xmlToUrl, just like you do in the following line of code:
{[xmlToUrlObject.name addObject:nodeContent];}
Here, xmlToUrlObject is an instance, and not the class.

CoverFlow multiple Views

Good Morning at all,
i have a big problem in the following code and no solution, so i hope someone could
help me:
- (IBAction)goToChart {
[rootViewController switchViews];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *weiter = [UIButton buttonWithType:UIButtonTypeRoundedRect];
weiter.frame = CGRectMake(100, 400, 120, 40);
[weiter addTarget:self action:#selector(goToChart) forControlEvents:UIControlEventTouchUpInside];
NSString *ansicht = #"Weiter";
[weiter setTitle:ansicht forState:UIControlStateNormal];
[self.view addSubview:weiter];
// loading images into the queue
loadImagesOperationQueue = [[NSOperationQueue alloc] init];
NSString *imageName;
for (int i=0; i < 10; i++) {
imageName = [[NSString alloc] initWithFormat:#"cover_%d.jpg", i];
imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
UIImage *aktuellesImage = imageView.image;
UIImage *scaledImage = [aktuellesImage scaleToSize:CGSizeMake(100.0f, 100.0f)];
[(AFOpenFlowView *)self.view setImage:scaledImage forIndex:i];
[imageName release];
NSLog(#"%d is the index",i);
}
[(AFOpenFlowView *)self.view setNumberOfImages:10];
}
So you can see there 10 Images in this CoverFlowView, but how could i find out the ACTUAL picture that is in front, to use this in another view??
Could someone help me, please?
Greetings Marco
-(void)openFlowView: (AFOpenFlowView *)openFlowView imageSelected:(int)index
{
AppDelegate_iPhone *appDelegate = (AppDelegate_iPhone *)[[UIApplication sharedApplication]delegate];
db_detail = (DB_data *)[self.GalleryArray objectAtIndex:index];
appDelegate.Id = db_detail.Id;
// NSLog(#"id: value is %d",db_detail.Id);
// NSLog(#"Name vlaue is: %#",db_detail.Name);
appDelegate.title = db_detail.Name;
DetailMovieViewController *ViewController = [[DetailMovieViewController alloc]init];
[self.navigationController pushViewController:ViewController animated:YES ];
[ViewController release];
[db_detail release];
}

Resources