iphone textview update while cycle running thread - iphone

I'm trying to create a typewriter effect.
my code works fine. My problem, and this ... UITextView fails to update in real time. this is my code:
NSMutableArray *testochar=[util getTestoChar:value];
for (int i=0; i<[testochar count]; i++){
NSString *y=[testochar objectAtIndex:i];
[NSThread sleepForTimeInterval:0.1f];
self.txtview.text=[self.txtview.text stringByAppendingString:y];
}

All modification on UI you should do in main thread, try use performSelectorOnMainThread:withObject:waitUntilDone:
call
//...
for(int i=0;i<[testochar count];i++){
NSString *y=[testochar objectAtIndex:i];
[NSThread sleepForTimeInterval:0.1f];
NSDictionary *arg = [NSDictionary dictionaryWithObjectAndKeys:
self.txtview, #"textView",
y, #"string", nil ];
[self performSelectorOnMainThread:#selector(updateTextForTextView:) withObject:arg waitUntilDone:NO];
}
//.....
-(void)updateTextForTextView:(NSDictionary*)arg {
NSString *string = [arg objectForKey:#"string"];
UITextView *textView = [arg objectForKey:#"textView"];
self.txtview.text=[self.txtview.text stringByAppendingString:string];
}
(update)
try
- (void)viewDidLoad {
[super viewDidLoad];
textView.text = #"";
[[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(update) userInfo:nil repeats:YES] retain];
}
-(void) update {
static char text[] = "HELLO";
static int i =0;
if (text[i%6]==0) {
textView.text = [NSString stringWithFormat:#""];
} else {
textView.text = [NSString stringWithFormat:#"%#%c", textView.text, text[i%6] ];
}
i++;
}
it works like:
http://www.youtube.com/watch?v=tB2YKX4zpY4

really thanks for your advice. I did it by modifying the code this way.
1) self.timer = [[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(update) userInfo:nil repeats:YES] retain];
-(void) update {
char text[[self.testo length]];
for(int i=0;i<self.testo.length;i++){
text[i]=[self.testo characterAtIndex:i];
}
static int i =0;
if (i==self.testo.length) {
/// txtview.text = [NSString stringWithFormat:#""];
[self.timer invalidate];
} else {
txtview.text = [NSString stringWithFormat:#"%#%c", txtview.text, text[i%self.testo.length] ];
}
i++;
}

Related

NSTimer stops when we click on ScrollView

In my app am using UIScrollView which is having UIImageView(20) to add images iused the - (void)populateScrollView method.
- (void)populateScrollView
{
TonifyAppDelegate *appDelegate = (TonifyAppDelegate *)[UIApplication sharedApplication].delegate;
double x1 = 0, y1 = 3;
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
NSMutableArray *getEffectsImageData = [ud objectForKey:#"getimageeffects"];
imageViewsArray = [[NSMutableArray alloc] initWithCapacity:[getEffectsImageData count]];
for(int i = 0; i < [getEffectsImageData count]; i++)
{
NSString *sfxUrlFileName = [ [getEffectsImageData objectAtIndex:i] lastPathComponent];
NSLog(#"sfxUrlFileName: %#", sfxUrlFileName);
NSData *imageData = [appDelegate readSongDataFromDocsDirectory:sfxUrlFileName];
UIImage *image = [[UIImage alloc] initWithData:imageData];
UIImageView *anImageView = [[UIImageView alloc]initWithImage:image];
CGRect imageFrame = anImageView.frame;
imageFrame.origin.x = x1;
imageFrame.origin.y = y1;
anImageView.frame = CGRectMake(x1, y1, 45, 41);
anImageView.userInteractionEnabled = YES;
[scrollView addSubview:anImageView];
x1 += anImageView.frame.size.width + 3;
if (anImageView && [anImageView isMemberOfClass: [UIImageView class]])
[imageViewsArray addObject: anImageView];
}
NSLog(#"imageViewsArray:%#",imageViewsArray);
}
And to recognize touch in UIScrollView i used
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(singleTapGestureCaptured:)];
[scrollView addGestureRecognizer:singleTap];
Meanwhile am running song by using NSTimer which is like
myTimer = [NSTimer scheduledTimerWithTimeInterval:timeinterval target:self selector:#selector(**updatplayer**) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:myTimer forMode:NSRunLoopCommonModes];
in updatePlayer method am doing task as follows
- (void)updatplayer
{
TonifyAppDelegate *appDelegate = (TonifyAppDelegate *)[UIApplication sharedApplication].delegate;
if (mThresholdVal<mMainLoopLength)
{
mThresholdVal+=0.5;
}
else
{
mThresholdVal = 0.0;
}
if (divimageView)
{
[divimageView removeFromSuperview];
}
if ([self isHeadsetPluggedIn]==NO) {
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
}
else
{
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_None;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
}
NSString *cu=[NSString stringWithFormat:#"%2.f",audioPlayer.currentTime];
NSString *du=[NSString stringWithFormat:#"%2.f",audioPlayer.duration];
NSLog(#"LOOP cu Duration = %#",cu);
NSLog(#"LOOP du = %#",du);
int curenttime=(int)[cu intValue];
NSLog(#"LOOP current Duration = %2.f",audioPlayer.duration);
if(curenttime==0)
{
[audioPlayer play];
x=20;
}
mixdata = [NSMutableDictionary dictionary];
{
[activityIndicator stopAnimating];
activityIndicator.hidden = YES;
[divimageView setFrame:CGRectMake(x, 87, 12, 144)];
[self.view addSubview:divimageView];
x=x+1;
if ((x>19 && x< 480) && appDelegate.songURL != NULL) {
[avplayer play];
NSLog(#"mixdata:%#", mixdata);
}
else if((x>19 && x< 480) && (appDelegate.songIntroUrl || appDelegate.songMidUrl || appDelegate.songChorusUrl) )
{
[audioPlayer play];
}
if (x==xCord && yCord<235)
{
[audioPlayer1 play];
}
if (x==recXcord)
{
recaudioPlayer.volume = 10.0;
[recaudioPlayer play];
[activityIndicator stopAnimating];
activityIndicator.hidden = YES;
}
if(appDelegate.xCordArray!=NULL && [appDelegate.tagArray count]>0)
{
for(int i = 0; i<[appDelegate.xCordArray count];i++)
{
if (i == 0){
NSLog(#"sfxCount in i==0......%d",sfxCount);
NSLog(#"[appDelegate.xCordArray count] in i==0......%d",[appDelegate.xCordArray count]);
NSLog(#"[appDelegate.mMixedSFXTrack2Array count] in i==0......%d",[appDelegate.mMixedSFXTrack2Array count]);
if (sfxCount-1 != [appDelegate.xCordArray count])
{
if ([appDelegate.xCordArray count] > [appDelegate.mMixedSFXTrack2Array count] )
{
mShouldBufferUpdate = TRUE;
sfxCount = [appDelegate.xCordArray count];
}
}
}
if (x==[[appDelegate.xCordArray objectAtIndex:i] intValue] && appDelegate.imgDragXCodr<480)
{
int j = [[appDelegate.tagArray objectAtIndex:i] intValue];
//mShouldBufferUpdate = TRUE;
[self getSetSongData:j :x];
[audioPlayer2 play];
}
}
}
if(appDelegate.xCordTrack3Array!=NULL && [appDelegate.track3tagArray count]>0)
{
for(int i = 0; i<[appDelegate.xCordTrack3Array count];i++)
{
if (i == 0)
{
if (sfxCount3-1 != [appDelegate.xCordTrack3Array count])
{
if ([appDelegate.xCordTrack3Array count] > [appDelegate.mMixedSFXTrack3Array count] )
{
mShouldBuffer3Update = TRUE;
sfxCount3 = [appDelegate.xCordTrack3Array count];
}
}
}
if (x==[[appDelegate.xCordTrack3Array objectAtIndex:i] intValue] && appDelegate.imgDragXCodr1<480)
{
int j = [[appDelegate.track3tagArray objectAtIndex:i] intValue];
[self getSetSongData:j :x];
[trac3AudioPlayer play]; //For SFX Sounds
}
}
}
if (x == 480)
{
x=20;
}
}
}
When i click on scrollView it generates an image in UIView(main View) at that time NSTimer is getting paused.
How can we solve this.
Any one can help or suggest me.
Thanks in advance.

Background thread running for fetching image from Facebook album

- (void)request:(FBRequest *)request didLoad:(id)result {
// NSArray *resultData = [result objectForKey:#"data"];
NSMutableArray *photos = [[NSMutableArray alloc] initWithCapacity:1];
// imageArray = [[NSMutableArray alloc] initWithCapacity:1];
NSArray *resultData = [result objectForKey:#"data"];
if ([resultData count] > 0)
{
noOfImages = 0;
for (NSUInteger i=0; i<[resultData count] ; i++)
{
[photos addObject:[resultData objectAtIndex:i]];
NSDictionary *albumPhotos = [photos objectAtIndex:i];
NSString *imageUrl = [albumPhotos objectForKey:#"picture"];
NSLog(#"ImageURL:%#",imageUrl);
NSURL *url = [NSURL URLWithString:imageUrl];
// [slideImageArray addObject:url];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *images = [UIImage imageWithData:data];
// imageView.image = images;
[slideImageArray addObject:images];
[NSThread detachNewThreadSelector:#selector(startTheBackgroundJob:) toTarget:self withObject:images];
}
NSLog(#"ImageCount:%d",[slideImageArray count]);
if([slideImageArray count] == 1)
{
imageView.image = [slideImageArray objectAtIndex:0];
}
if([slideImageArray count]>1)
{
numTimer =0;
myTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:#selector(timerRunning) userInfo:nil repeats:YES];
}
}
}
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
NSLog(#"Err message: %#", [[error userInfo] objectForKey:#"error_msg"]);
NSLog(#"Err code: %d", [error code]);
}
- (void)startTheBackgroundJob:(UIImage *)img
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// wait for 3 seconds before starting the thread, you don't have to do that. This is just an example how to stop the NSThread for some time
//imageView.image = img;
noOfImages++;
// [NSThread sleepForTimeInterval:3];
// [slideImageArray addObject:img];
//[NSThread sleepForTimeInterval:1];
imageView.image = img;
if(noOfImages == 1)
{
NSLog(#"noValueif:%d",noOfImages);
// imageView.image = [slideImageArray objectAtIndex:0];
[NSThread sleepForTimeInterval:1];
// imageView.image = img;
}
else if(noOfImages >1)
{
NSLog(#"noValue:%d",noOfImages);
// numTimer =0;
// myTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:#selector(timerRunning) userInfo:nil repeats:YES];
// imageView.image = img;
[NSThread sleepForTimeInterval:3];
}
// [self performSelectorOnMainThread:#selector(changeImageViewImage) withObject:nil waitUntilDone:NO];
[pool release];
}
I have to run a background thread for getting image from Facebook album .i have to start a slide show with the first image collected.and i given a sleep for 3 second but it is not working.Also is there any other method for getting image from url other than the NSData *data = [NSData dataWithContentsOfURL:url]; method
Did you ever find the answer for this question?? or were u able to solve it?
And for this facebook api, are you using a personalized subclass of NSThread or using Dispatch queues?
And to answer your question if you want to fetch data in the background use performSelectorONMainThread... some facebook SDK methods require to be runned on the main thread for them to work, in my personal experience i found out that most of the data requesting is necessary to be on the mainthread using this method.
It worked for me, hopefully it works for you
:).

Drawing the polyline on the map in iphone

Friend
I am trying to Drawing the polyline on the map. For that I use this code. It work fine. Over here I use Fake_location(CSV file) but if I to want use the database location... My database table is like this:
PK LocationID VARCHAR(20)
_id INTEGER
FK1 JourneyID VARCHAR(20)
Altitude FLOAT
Longitude FLOAT
Latitude FLOAT
Speed FLOAT
Accuracy FLOAT
LocationDate DATETIME
LastSyncDate DATETIME
How can I use Longitude & Latitude ?
-(id)init {
self = [super init];
NSString* filePath = [[NSBundle mainBundle] pathForResource:ROUTE_FILE_NAME ofType:#"csv"];
NSString *fake_location = [[NSString alloc] initWithContentsOfFile:filePath];
pointsArray = [[fake_location componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] retain];
pointsArrayIndex = 0;
oldLocationsIndex = 0;
[fake_location release];
oldLocations = [[NSMutableArray alloc] init];
return self;
}
-(void)startUpdatingLocation {
aTimer = [NSTimer scheduledTimerWithTimeInterval:TIMER_INTERVAL target:self selector:#selector(injectNextLocation) userInfo:nil repeats:YES];
}
-(void)stopUpdatingLocation {
[aTimer invalidate];
}
-(void)injectNextLocation{
if (pointsArray.count == pointsArrayIndex) {
[self stopUpdatingLocation];
return;
}
CLLocation *oldLocation = nil;
if ([oldLocations count] > 0) {
oldLocation = [oldLocations objectAtIndex:oldLocationsIndex];
oldLocationsIndex++;
}
NSString *pointString = [pointsArray objectAtIndex:pointsArrayIndex];
NSArray *latLong = [pointString componentsSeparatedByString:#","];
//NSLog(#"%#",latLong);
CLLocationCoordinate2D coords;
coords.latitude = [[latLong objectAtIndex:0] doubleValue];
coords.longitude = [[latLong objectAtIndex:1] doubleValue];
float altitude = [self getRandomValue:200 toMax:220];
CLLocation *myLocation = [[CLLocation alloc] initWithCoordinate:coords altitude:altitude horizontalAccuracy:1 verticalAccuracy:1 timestamp:[NSDate date]];
[self.delegate locationManager:self didUpdateToLocation:myLocation fromLocation:oldLocation];
[oldLocations addObject:myLocation];
[myLocation release];
pointsArrayIndex++;
}
-(void)dealloc {
[pointsArray release];
[aTimer release];
[oldLocations release];
[super dealloc];
}
#pragma mark -
#pragma mark functions
- (float) getRandomValue:(float)min toMax:(float)max {
NSNumber *rand;
rand = [NSNumber numberWithUnsignedInt:arc4random()];
return fmod([rand floatValue],(max-min+1))+min;
}

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 ;)