Search Results

Search found 83 results on 4 pages for 'graeme donaldson'.

Page 2/4 | < Previous Page | 1 2 3 4  | Next Page >

  • Can a method return an NSRange?

    - by Dan Donaldson
    I have a method that returns an NSRange. When I call this method from outside the class I get a compile error. NSRange tmpRange; tmpRange = [phrase rangeInString:searchString forString:theLetter goingForward:YES]; return tmpRange.location == -1; in the .h file: #import <Foundation/Foundation.h> @interface Phrase : NSObject { } - (NSRange) rangeInString:(NSString *) tgt forString:(NSString *) find goingForward:(BOOL) fwd; @end This method is called within the Phrase object by other methods without problems. The compiler says 'incompatible types in assignment'. Can anyone explain this to me? I assume it has to do with returning an NSRange/struct type value generated outside the object, but I don't know why it works in one place and not the other.

    Read the article

  • Adding value of cell X only if cell Y is blank

    - by Graeme Hutchison
    I have a list with three columns A, B, and C. The first two columns are complete (A and B), while the third (C) has many blanked fields. What I want to do is replace all the blank fields in Column C with the same value form cell A in the same row. The List contains over 2000 records, of which 65% have a blank Column C value, so I would like to use a formula/function. Below is an example of what I have and what I want to do (on a much smaller scale)

    Read the article

  • Pivot Table from data with merged cells

    - by Graeme
    I have a energy spreadsheet for multiple sites. the first row has month and year. the next row has columns for date invoice received, KW hours and cost. So there are three columns for each month. I have merged the month cell across the three columns. When i create a pivot table the date kw/h and costs are labled date1, date2, etc. Can I link the months headings to the subheadings to get meaningful headings in the pivot table????

    Read the article

  • Scrolling an HTML 5 page using JQuery

    - by nikolaosk
    In this post I will show you how to use JQuery to scroll through an HTML 5 page.I had to help a friend of mine to implement this functionality and I thought it would be a good idea to write a post.I will not use any JQuery scrollbar plugin,I will just use the very popular JQuery Library. Please download the library (minified version) from http://jquery.com/download.Please find here all my posts regarding JQuery.Also have a look at my posts regarding HTML 5.In order to be absolutely clear this is not (and could not be) a detailed tutorial on HTML 5. There are other great resources for that.Navigate to the excellent interactive tutorials of W3School.Another excellent resource is HTML 5 Doctor.Two very nice sites that show you what features and specifications are implemented by various browsers and their versions are http://caniuse.com/ and http://html5test.com/. At this times Chrome seems to support most of HTML 5 specifications.Another excellent way to find out if the browser supports HTML 5 and CSS 3 features is to use the Javascript lightweight library Modernizr.In this hands-on example I will be using Expression Web 4.0.This application is not a free application. You can use any HTML editor you like.You can use Visual Studio 2012 Express edition. You can download it here. Let me move on to the actual example.This is the sample HTML 5 page<!DOCTYPE html><html lang="en">  <head>    <title>Liverpool Legends</title>        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >        <link rel="stylesheet" type="text/css" href="style.css">        <script type="text/javascript" src="jquery-1.8.2.min.js"> </script>     <script type="text/javascript" src="scroll.js">     </script>       </head>  <body>    <header>        <h1>Liverpool Legends</h1>    </header>        <div id="main">        <table>        <caption>Liverpool Players</caption>        <thead>            <tr>                <th>Name</th>                <th>Photo</th>                <th>Position</th>                <th>Age</th>                <th>Scroll</th>            </tr>        </thead>        <tfoot class="footnote">            <tr>                <td colspan="4">We will add more photos soon</td>            </tr>        </tfoot>    <tbody>        <tr class="maintop">        <td>Alan Hansen</td>            <td>            <figure>            <img src="images\Alan-hansen-large.jpg" alt="Alan Hansen">            <figcaption>The best Liverpool Defender <a href="http://en.wikipedia.org/wiki/Alan_Hansen">Alan Hansen</a></figcaption>            </figure>            </td>            <td>Defender</td>            <td>57</td>            <td class="top">Middle</td>        </tr>        <tr>        <td>Graeme Souness</td>            <td>            <figure>            <img src="images\graeme-souness-large.jpg" alt="Graeme Souness">            <figcaption>Souness was the captain of the successful Liverpool team of the early 1980s <a href="http://en.wikipedia.org/wiki/Graeme_Souness">Graeme Souness</a></figcaption>            </figure>            </td>            <td>MidFielder</td>            <td>59</td>        </tr>        <tr>        <td>Ian Rush</td>            <td>            <figure>            <img src="images\ian-rush-large.jpg" alt="Ian Rush">            <figcaption>The deadliest Liverpool Striker <a href="http://it.wikipedia.org/wiki/Ian_Rush">Ian Rush</a></figcaption>            </figure>            </td>            <td>Striker</td>            <td>51</td>        </tr>        <tr class="mainmiddle">        <td>John Barnes</td>            <td>            <figure>            <img src="images\john-barnes-large.jpg" alt="John Barnes">            <figcaption>The best Liverpool Defender <a href="http://en.wikipedia.org/wiki/John_Barnes_(footballer)">John Barnes</a></figcaption>            </figure>            </td>            <td>MidFielder</td>            <td>49</td>            <td class="middle">Bottom</td>        </tr>                <tr>        <td>Kenny Dalglish</td>            <td>            <figure>            <img src="images\kenny-dalglish-large.jpg" alt="Kenny Dalglish">            <figcaption>King Kenny <a href="http://en.wikipedia.org/wiki/Kenny_Dalglish">Kenny Dalglish</a></figcaption>            </figure>            </td>            <td>Midfielder</td>            <td>61</td>        </tr>        <tr>            <td>Michael Owen</td>            <td>            <figure>            <img src="images\michael-owen-large.jpg" alt="Michael Owen">            <figcaption>Michael was Liverpool's top goal scorer from 1997–2004 <a href="http://www.michaelowen.com/">Michael Owen</a></figcaption>            </figure>            </td>            <td>Striker</td>            <td>33</td>        </tr>        <tr>            <td>Robbie Fowler</td>            <td>            <figure>            <img src="images\robbie-fowler-large.jpg" alt="Robbie Fowler">            <figcaption>Fowler scored 183 goals in total for Liverpool <a href="http://en.wikipedia.org/wiki/Robbie_Fowler">Robbie Fowler</a></figcaption>            </figure>            </td>            <td>Striker</td>            <td>38</td>        </tr>        <tr class="mainbottom">            <td>Steven Gerrard</td>            <td>            <figure>            <img src="images\steven-gerrard-large.jpg" alt="Steven Gerrard">            <figcaption>Liverpool's captain <a href="http://en.wikipedia.org/wiki/Steven_Gerrard">Steven Gerrard</a></figcaption>            </figure>            </td>            <td>Midfielder</td>            <td>32</td>            <td class="bottom">Top</td>        </tr>    </tbody></table>          </div>            <footer>        <p>All Rights Reserved</p>      </footer>     </body>  </html>  The markup is very easy to follow and understand. You do not have to type all the code,simply copy and paste it.For those that you are not familiar with HTML 5, please take a closer look at the new tags/elements introduced with HTML 5.When I view the HTML 5 page with Firefox I see the following result. I have also an external stylesheet (style.css). body{background-color:#efefef;}h1{font-size:2.3em;}table { border-collapse: collapse;font-family: Futura, Arial, sans-serif; }caption { font-size: 1.2em; margin: 1em auto; }th, td {padding: .65em; }th, thead { background: #000; color: #fff; border: 1px solid #000; }tr:nth-child(odd) { background: #ccc; }tr:nth-child(even) { background: #404040; }td { border-right: 1px solid #777; }table { border: 1px solid #777;  }.top, .middle, .bottom {    cursor: pointer;    font-size: 22px;    font-weight: bold;    text-align: center;}.footnote{text-align:center;font-family:Tahoma;color:#EB7515;}a{color:#22577a;text-decoration:none;}     a:hover {color:#125949; text-decoration:none;}  footer{background-color:#505050;width:1150px;}These are just simple CSS Rules that style the various HTML 5 tags,classes. The jQuery code that makes it all possible resides inside the scroll.js file.Make sure you type everything correctly.$(document).ready(function() {                 $('.top').click(function(){                     $('html, body').animate({                         scrollTop: $(".mainmiddle").offset().top                     },4000 );                  });                 $('.middle').click(function(){                     $('html, body').animate({                         scrollTop: $(".mainbottom").offset().top                     },4000);                  });                     $('.bottom').click(function(){                     $('html, body').animate({                         scrollTop: $(".maintop").offset().top                     },4000);                  }); });  Let me explain what I am doing here.When I click on the Middle word (  $('.top').click(function(){ ) this relates to the top class that is clicked.Then we declare the elements that we want to participate in the scrolling. In this case is html,body ( $('html, body').animate).These elements will be part of the vertical scrolling.In the next line of code we simply move (navigate) to the element (class mainmiddle that is attached to a tr element.)      scrollTop: $(".mainmiddle").offset().top  Make sure you type all the code correctly and try it for yourself. I have tested this solution will all 4-5 major browsers.Hope it helps!!!

    Read the article

  • Three20 TTLauncherView Tutorial?

    - by Graeme
    Hi, I'm attempting to use TTLauncherView from the Facebook Three20 project in my app, but I'm not having much luck (I'm a bit of a newbie at this). Does anyone have any good tutorials at using it that I could read? FYI basically I need to pull images that a user chooses from the iPhone camera album, and display them as icons that when pressed lead to another view. Thanks.

    Read the article

  • Core Data Error "Fetch Request must have an entity"

    - by Graeme
    Hi, I've attempted to add the TopSongs parser and Core Data files into my application, and it now builds succesfully, with no errors or warning messages. However, as soon as the app loads, it crashes, giving the following reason: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'executeFetchRequest:error: A fetch request must have an entity.' I have renamed all files, including the .xcdatamodel file. Could this be the problem (the renaming of the .xcdatamodel)? I'm assuming this error means that no data can be found. Thanks.

    Read the article

  • What is the "stringWithContentsOfURL" replacement for objective C?

    - by Graeme
    I found a tutorial on the net that uses the stringWithContentsOfURL command that is now deprecated as of iPhone OS 3.0. However I can't find out what I'm meant to use instead, and how to implement it. Below is the code surrounding the stringWithContentsOfURL line in case you need it for reference. NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv", [addressField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]]; NSArray *listItems = [locationString componentsSeparatedByString:@","]; Thanks.

    Read the article

  • log4net affecting other projects which don't even use it

    - by Graeme
    I'm seeing something really strange happening with some projects I'm working on. I used log4net in an MVC web site and this was working great. I then was working on a totally unrelated Console application which uses the SharePoint API and as soon as I include the following line (other lines don't cause the problem) SPLimitedWebPartManager spWebPartManager = web.GetLimitedWebPartManager("http://blah/blah.aspx?PageView=Shared", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared); I get the following message in the console app log4net:ERROR XmlConfigurator: Failed to find configuration section 'log4net' in the application's .config file. Check your .config file for the <log4net> and < configSections> elements. The configuration section should look like: <section n ame="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" / > log4net:ERROR XmlConfigurator: Failed to find configuration section 'log4net' in the application's .config file. Check your .config file for the <log4net> and < configSections> elements. The configuration section should look like: <section n ame="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" / > I get this twice after a small delay. The delay is probably the request to get the web part manager from the page but I'm not sure why this log4net error is showing up in this project. I've gone through the code and bin folders etc. and found no trace of any log4net mentions. Any ideas why this might be happening?

    Read the article

  • UIImages not displaying in TableView on iPhone, but working in Simulator

    - by Graeme
    Hi, I have a UITable View that displays an image in the left hand side of the table cell, and it works fine in the simulator. Only problem is, once I ran it on my device no images appear. It's just a blank white space. Have checked that images are added to resource folder for build (which they are) and that capitals etc. match (which they do). Any ideas? Thanks. Code to display images: cell.imageView.layer.masksToBounds = YES; cell.imageView.layer.cornerRadius = 5.0; UIImage *image = [UIImage imageNamed:[[dog types] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];; if ( image ) { cell.imageView.image = [image imageScaledToSize:CGSizeMake(50, 50)]; }

    Read the article

  • swfobject in Uploadify not working with IE 7 or 8

    - by Graeme
    I am using Uploadify and have a pop up which is loaded by jQuery by Ajax. The page on which the popup lives on has an include to swfobject (from Google's Code Api) and the Uploadify button should appear. This works great on FF and Chrome but IE gives me a javascript error Unknown runtime error line 4 character 5942 Anyone got any ideas how to fix this problem? It's possibly to do with the fact that I'm using it from within dynamic content. I found the following link but there is no definitive answer Possible answer

    Read the article

  • UITableView not displaying parsed data

    - by Graeme
    I have a UITableView which is setup in Interface Builder and connected properly to its class in Xcode. I also have a "Importer" Class which downloads and parses an RSS feed and stores the information in an NSMutableArray. However I have verified the parsing is working properly (using breakpoints and NSlog) but no data is showing in the UITable View. Any ideas as to what the problem could be? I'm almost out of them. It's based on the XML performance Apple example. Here's the code for TableView.h: #import <UIKit/UIKit.h> #import "IncidentsImporter.h" @class SongDetailsController; @interface CurrentIncidentsTableViewController : UITableViewController <IncidentsImporterDelegate>{ NSMutableArray *incidents; SongDetailsController *detailController; UITableView *ctableView; IncidentsImporter *parser; } @property (nonatomic, retain) NSMutableArray *incidents; @property (nonatomic, retain, readonly) SongDetailsController *detailController; @property (nonatomic, retain) IncidentsImporter *parser; @property (nonatomic, retain) IBOutlet UITableView *ctableView; // Called by the ParserChoiceViewController based on the selected parser type. - (void)beginParsing; @end And the code for .m: #import "CurrentIncidentsTableViewController.h" #import "SongDetailsController.h" #import "Incident.h" @implementation CurrentIncidentsTableViewController @synthesize ctableView, incidents, parser, detailController; #pragma mark - #pragma mark View lifecycle - (void)viewDidLoad { [super viewDidLoad]; self.parser = [[IncidentsImporter alloc] init]; parser.delegate = self; [parser start]; UIBarButtonItem *refreshButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(beginParsing)]; self.navigationItem.rightBarButtonItem = refreshButton; [refreshButton release]; // Uncomment the following line to preserve selection between presentations. //self.clearsSelectionOnViewWillAppear = NO; // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem; } - (void)viewWillAppear:(BOOL)animated { NSIndexPath *selectedRowIndexPath = [ctableView indexPathForSelectedRow]; if (selectedRowIndexPath != nil) { [ctableView deselectRowAtIndexPath:selectedRowIndexPath animated:NO]; } } // This method will be called repeatedly - once each time the user choses to parse. - (void)beginParsing { NSLog(@"Parsing has begun"); //self.navigationItem.rightBarButtonItem.enabled = NO; // Allocate the array for song storage, or empty the results of previous parses if (incidents == nil) { NSLog(@"Grabbing array"); self.incidents = [NSMutableArray array]; } else { [incidents removeAllObjects]; [ctableView reloadData]; } // Create the parser, set its delegate, and start it. self.parser = [[IncidentsImporter alloc] init]; parser.delegate = self; [parser start]; } /* - (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 { // Override to allow orientations other than the default portrait orientation. return YES; } #pragma mark - #pragma mark Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Return the number of rows in the section. return [incidents count]; } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSLog(@"Table Cell Sought"); static NSString *kCellIdentifier = @"MyCell"; UITableViewCell *cell = [ctableView dequeueReusableCellWithIdentifier:kCellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellIdentifier] autorelease]; cell.textLabel.font = [UIFont boldSystemFontOfSize:14.0]; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; } cell.textLabel.text = @"Test";//[[incidents objectAtIndex:indexPath.row] title]; return cell; } /* // Override to support conditional editing of the table view. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the specified item to be editable. return YES; } */ /* // Override to support editing the table view. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete the row from the data source [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES]; } else if (editingStyle == UITableViewCellEditingStyleInsert) { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath { } */ /* // Override to support conditional rearranging of the table view. - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the item to be re-orderable. return YES; } */ #pragma mark - #pragma mark Table view delegate - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { self.detailController.incident = [incidents objectAtIndex:indexPath.row]; [self.navigationController pushViewController:self.detailController animated:YES]; } #pragma mark - #pragma mark Memory management - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Relinquish ownership any cached data, images, etc that aren't in use. } - (void)viewDidUnload { // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand. // For example: self.myOutlet = nil; } - (void)parserDidEndParsingData:(IncidentsImporter *)parser { [ctableView reloadData]; self.navigationItem.rightBarButtonItem.enabled = YES; self.parser = nil; } - (void)parser:(IncidentsImporter *)parser didParseIncidents:(NSArray *)parsedIncidents { //[incidents addObjectsFromArray: parsedIncidents]; // Three scroll view properties are checked to keep the user interface smooth during parse. When new objects are delivered by the parser, the table view is reloaded to display them. If the table is reloaded while the user is scrolling, this can result in eratic behavior. dragging, tracking, and decelerating can be checked for this purpose. When the parser finishes, reloadData will be called in parserDidEndParsingData:, guaranteeing that all data will ultimately be displayed even if reloadData is not called in this method because of user interaction. if (!ctableView.dragging && !ctableView.tracking && !ctableView.decelerating) { self.title = [NSString stringWithFormat:NSLocalizedString(@"Top %d Songs", @"Top Songs format"), [parsedIncidents count]]; [ctableView reloadData]; } } - (void)parser:(IncidentsImporter *)parser didFailWithError:(NSError *)error { // handle errors as appropriate to your application... } - (void)dealloc { [super dealloc]; } @end

    Read the article

  • Site Actions menu in SharePoint is WSS-like, whereas I have installed MOSS

    - by Graeme
    I had WSS installed on my VM and then uninstalled in order to install MOSS Enterprise I can see a lot of the MOSS stuff in the Central Administration pages but when I create a new web application and site collection, my Site Actions dropdown is showing the WSS version, i.e. Create, Edit Page and Site Settings as opposed to the MOSS menu which has View All Site Content, View Reports, Manage Content and Structure etc. I just tried deleting my web app and creating it all again but it's come back with the same thing again. Is somewhere remembering that I used to have WSS installed? (yes I know MOSS is built on top of WSS but you know what I mean!)

    Read the article

  • Problems extracting information from RSS feed description field

    - by Graeme
    Hi, I've built an iPhone application using the parsing code from the TopSongs sample iPhone application. I've hit a problem though - the feed I'm trying to parse data from doesn't have a separate field for every piece of information (i.e. if it was for a feed about dogs, all the information such as dog type, dog age and dog price is contained in the feed. However, the TopSongs app relies on information having its own tags, so instead of using it uses and . So my question is this. How do I extract this information from the description field so that it can be parsed using the TopSongs parser? Can you somehow extract the dog age, price and type information using Yahoo Pipes and use that RSS feed for the feed? Or is there code that I can add to do it in application? Update: To view the code of my application parser (based on the TopSongs Core Data Apple provided application, see below. Here's a sample of one item from the the actual RSS feed I'm using (the description is longer, and has status,size, and a couple of other fields, but they're all formatted the same.: <item> <title>MOE, MARGRET STREET</title> <description> <b>District/Region:</b>&nbsp;REGION 09</br><b>Location:</b>&nbsp;MOE</br><b>Name:</b>&nbsp;MARGRET STREET</br></description> <pubDate>Thu,11 Mar 2010 05:43:03 GMT</pubDate> <guid>1266148</guid> </item> /* File: iTunesRSSImporter.m Abstract: Downloads, parses, and imports the iTunes top songs RSS feed into Core Data. Version: 1.1 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Copyright (C) 2009 Apple Inc. All Rights Reserved. */ #import "iTunesRSSImporter.h" #import "Song.h" #import "Category.h" #import "CategoryCache.h" #import <libxml/tree.h> // Function prototypes for SAX callbacks. This sample implements a minimal subset of SAX callbacks. // Depending on your application's needs, you might want to implement more callbacks. static void startElementSAX(void *context, const xmlChar *localname, const xmlChar *prefix, const xmlChar *URI, int nb_namespaces, const xmlChar **namespaces, int nb_attributes, int nb_defaulted, const xmlChar **attributes); static void endElementSAX(void *context, const xmlChar *localname, const xmlChar *prefix, const xmlChar *URI); static void charactersFoundSAX(void *context, const xmlChar *characters, int length); static void errorEncounteredSAX(void *context, const char *errorMessage, ...); // Forward reference. The structure is defined in full at the end of the file. static xmlSAXHandler simpleSAXHandlerStruct; // Class extension for private properties and methods. @interface iTunesRSSImporter () @property BOOL storingCharacters; @property (nonatomic, retain) NSMutableData *characterBuffer; @property BOOL done; @property BOOL parsingASong; @property NSUInteger countForCurrentBatch; @property (nonatomic, retain) Song *currentSong; @property (nonatomic, retain) NSURLConnection *rssConnection; @property (nonatomic, retain) NSDateFormatter *dateFormatter; // The autorelease pool property is assign because autorelease pools cannot be retained. @property (nonatomic, assign) NSAutoreleasePool *importPool; @end static double lookuptime = 0; @implementation iTunesRSSImporter @synthesize iTunesURL, delegate, persistentStoreCoordinator; @synthesize rssConnection, done, parsingASong, storingCharacters, currentSong, countForCurrentBatch, characterBuffer, dateFormatter, importPool; - (void)dealloc { [iTunesURL release]; [characterBuffer release]; [currentSong release]; [rssConnection release]; [dateFormatter release]; [persistentStoreCoordinator release]; [insertionContext release]; [songEntityDescription release]; [theCache release]; [super dealloc]; } - (void)main { self.importPool = [[NSAutoreleasePool alloc] init]; if (delegate && [delegate respondsToSelector:@selector(importerDidSave:)]) { [[NSNotificationCenter defaultCenter] addObserver:delegate selector:@selector(importerDidSave:) name:NSManagedObjectContextDidSaveNotification object:self.insertionContext]; } done = NO; self.dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; [dateFormatter setDateStyle:NSDateFormatterLongStyle]; [dateFormatter setTimeStyle:NSDateFormatterNoStyle]; // necessary because iTunes RSS feed is not localized, so if the device region has been set to other than US // the date formatter must be set to US locale in order to parse the dates [dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"US"] autorelease]]; self.characterBuffer = [NSMutableData data]; NSURLRequest *theRequest = [NSURLRequest requestWithURL:iTunesURL]; // create the connection with the request and start loading the data rssConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; // This creates a context for "push" parsing in which chunks of data that are not "well balanced" can be passed // to the context for streaming parsing. The handler structure defined above will be used for all the parsing. // The second argument, self, will be passed as user data to each of the SAX handlers. The last three arguments // are left blank to avoid creating a tree in memory. context = xmlCreatePushParserCtxt(&simpleSAXHandlerStruct, self, NULL, 0, NULL); if (rssConnection != nil) { do { [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; } while (!done); } // Display the total time spent finding a specific object for a relationship NSLog(@"lookup time %f", lookuptime); // Release resources used only in this thread. xmlFreeParserCtxt(context); self.characterBuffer = nil; self.dateFormatter = nil; self.rssConnection = nil; self.currentSong = nil; [theCache release]; theCache = nil; NSError *saveError = nil; NSAssert1([insertionContext save:&saveError], @"Unhandled error saving managed object context in import thread: %@", [saveError localizedDescription]); if (delegate && [delegate respondsToSelector:@selector(importerDidSave:)]) { [[NSNotificationCenter defaultCenter] removeObserver:delegate name:NSManagedObjectContextDidSaveNotification object:self.insertionContext]; } if (self.delegate != nil && [self.delegate respondsToSelector:@selector(importerDidFinishParsingData:)]) { [self.delegate importerDidFinishParsingData:self]; } [importPool release]; self.importPool = nil; } - (NSManagedObjectContext *)insertionContext { if (insertionContext == nil) { insertionContext = [[NSManagedObjectContext alloc] init]; [insertionContext setPersistentStoreCoordinator:self.persistentStoreCoordinator]; } return insertionContext; } - (void)forwardError:(NSError *)error { if (self.delegate != nil && [self.delegate respondsToSelector:@selector(importer:didFailWithError:)]) { [self.delegate importer:self didFailWithError:error]; } } - (NSEntityDescription *)songEntityDescription { if (songEntityDescription == nil) { songEntityDescription = [[NSEntityDescription entityForName:@"Song" inManagedObjectContext:self.insertionContext] retain]; } return songEntityDescription; } - (CategoryCache *)theCache { if (theCache == nil) { theCache = [[CategoryCache alloc] init]; theCache.managedObjectContext = self.insertionContext; } return theCache; } - (Song *)currentSong { if (currentSong == nil) { currentSong = [[Song alloc] initWithEntity:self.songEntityDescription insertIntoManagedObjectContext:self.insertionContext]; } return currentSong; } #pragma mark NSURLConnection Delegate methods // Forward errors to the delegate. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { [self performSelectorOnMainThread:@selector(forwardError:) withObject:error waitUntilDone:NO]; // Set the condition which ends the run loop. done = YES; } // Called when a chunk of data has been downloaded. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { // Process the downloaded chunk of data. xmlParseChunk(context, (const char *)[data bytes], [data length], 0); } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { // Signal the context that parsing is complete by passing "1" as the last parameter. xmlParseChunk(context, NULL, 0, 1); context = NULL; // Set the condition which ends the run loop. done = YES; } #pragma mark Parsing support methods static const NSUInteger kImportBatchSize = 20; - (void)finishedCurrentSong { parsingASong = NO; self.currentSong = nil; countForCurrentBatch++; // Periodically purge the autorelease pool and save the context. The frequency of this action may need to be tuned according to the // size of the objects being parsed. The goal is to keep the autorelease pool from growing too large, but // taking this action too frequently would be wasteful and reduce performance. if (countForCurrentBatch == kImportBatchSize) { [importPool release]; self.importPool = [[NSAutoreleasePool alloc] init]; NSError *saveError = nil; NSAssert1([insertionContext save:&saveError], @"Unhandled error saving managed object context in import thread: %@", [saveError localizedDescription]); countForCurrentBatch = 0; } } /* Character data is appended to a buffer until the current element ends. */ - (void)appendCharacters:(const char *)charactersFound length:(NSInteger)length { [characterBuffer appendBytes:charactersFound length:length]; } - (NSString *)currentString { // Create a string with the character data using UTF-8 encoding. UTF-8 is the default XML data encoding. NSString *currentString = [[[NSString alloc] initWithData:characterBuffer encoding:NSUTF8StringEncoding] autorelease]; [characterBuffer setLength:0]; return currentString; } @end #pragma mark SAX Parsing Callbacks // The following constants are the XML element names and their string lengths for parsing comparison. // The lengths include the null terminator, to ensure exact matches. static const char *kName_Item = "item"; static const NSUInteger kLength_Item = 5; static const char *kName_Title = "title"; static const NSUInteger kLength_Title = 6; static const char *kName_Category = "category"; static const NSUInteger kLength_Category = 9; static const char *kName_Itms = "itms"; static const NSUInteger kLength_Itms = 5; static const char *kName_Artist = "description"; static const NSUInteger kLength_Artist = 7; static const char *kName_Album = "description"; static const NSUInteger kLength_Album = 6; static const char *kName_ReleaseDate = "releasedate"; static const NSUInteger kLength_ReleaseDate = 12; /* This callback is invoked when the importer finds the beginning of a node in the XML. For this application, out parsing needs are relatively modest - we need only match the node name. An "item" node is a record of data about a song. In that case we create a new Song object. The other nodes of interest are several of the child nodes of the Song currently being parsed. For those nodes we want to accumulate the character data in a buffer. Some of the child nodes use a namespace prefix. */ static void startElementSAX(void *parsingContext, const xmlChar *localname, const xmlChar *prefix, const xmlChar *URI, int nb_namespaces, const xmlChar **namespaces, int nb_attributes, int nb_defaulted, const xmlChar **attributes) { iTunesRSSImporter *importer = (iTunesRSSImporter *)parsingContext; // The second parameter to strncmp is the name of the element, which we known from the XML schema of the feed. // The third parameter to strncmp is the number of characters in the element name, plus 1 for the null terminator. if (prefix == NULL && !strncmp((const char *)localname, kName_Item, kLength_Item)) { importer.parsingASong = YES; } else if (importer.parsingASong && ( (prefix == NULL && (!strncmp((const char *)localname, kName_Title, kLength_Title) || !strncmp((const char *)localname, kName_Category, kLength_Category))) || ((prefix != NULL && !strncmp((const char *)prefix, kName_Itms, kLength_Itms)) && (!strncmp((const char *)localname, kName_Artist, kLength_Artist) || !strncmp((const char *)localname, kName_Album, kLength_Album) || !strncmp((const char *)localname, kName_ReleaseDate, kLength_ReleaseDate))) )) { importer.storingCharacters = YES; } } /* This callback is invoked when the parse reaches the end of a node. At that point we finish processing that node, if it is of interest to us. For "item" nodes, that means we have completed parsing a Song object. We pass the song to a method in the superclass which will eventually deliver it to the delegate. For the other nodes we care about, this means we have all the character data. The next step is to create an NSString using the buffer contents and store that with the current Song object. */ static void endElementSAX(void *parsingContext, const xmlChar *localname, const xmlChar *prefix, const xmlChar *URI) { iTunesRSSImporter *importer = (iTunesRSSImporter *)parsingContext; if (importer.parsingASong == NO) return; if (prefix == NULL) { if (!strncmp((const char *)localname, kName_Item, kLength_Item)) { [importer finishedCurrentSong]; } else if (!strncmp((const char *)localname, kName_Title, kLength_Title)) { importer.currentSong.title = importer.currentString; } else if (!strncmp((const char *)localname, kName_Category, kLength_Category)) { double before = [NSDate timeIntervalSinceReferenceDate]; Category *category = [importer.theCache categoryWithName:importer.currentString]; double delta = [NSDate timeIntervalSinceReferenceDate] - before; lookuptime += delta; importer.currentSong.category = category; } } else if (!strncmp((const char *)prefix, kName_Itms, kLength_Itms)) { if (!strncmp((const char *)localname, kName_Artist, kLength_Artist)) { NSString *string = importer.currentSong.artist; NSArray *strings = [string componentsSeparatedByString: @", "]; //importer.currentSong.artist = importer.currentString; } else if (!strncmp((const char *)localname, kName_Album, kLength_Album)) { importer.currentSong.album = importer.currentString; } else if (!strncmp((const char *)localname, kName_ReleaseDate, kLength_ReleaseDate)) { NSString *dateString = importer.currentString; importer.currentSong.releaseDate = [importer.dateFormatter dateFromString:dateString]; } } importer.storingCharacters = NO; } /* This callback is invoked when the parser encounters character data inside a node. The importer class determines how to use the character data. */ static void charactersFoundSAX(void *parsingContext, const xmlChar *characterArray, int numberOfCharacters) { iTunesRSSImporter *importer = (iTunesRSSImporter *)parsingContext; // A state variable, "storingCharacters", is set when nodes of interest begin and end. // This determines whether character data is handled or ignored. if (importer.storingCharacters == NO) return; [importer appendCharacters:(const char *)characterArray length:numberOfCharacters]; } /* A production application should include robust error handling as part of its parsing implementation. The specifics of how errors are handled depends on the application. */ static void errorEncounteredSAX(void *parsingContext, const char *errorMessage, ...) { // Handle errors as appropriate for your application. NSCAssert(NO, @"Unhandled error encountered during SAX parse."); } // The handler struct has positions for a large number of callback functions. If NULL is supplied at a given position, // that callback functionality won't be used. Refer to libxml documentation at http://www.xmlsoft.org for more information // about the SAX callbacks. static xmlSAXHandler simpleSAXHandlerStruct = { NULL, /* internalSubset */ NULL, /* isStandalone */ NULL, /* hasInternalSubset */ NULL, /* hasExternalSubset */ NULL, /* resolveEntity */ NULL, /* getEntity */ NULL, /* entityDecl */ NULL, /* notationDecl */ NULL, /* attributeDecl */ NULL, /* elementDecl */ NULL, /* unparsedEntityDecl */ NULL, /* setDocumentLocator */ NULL, /* startDocument */ NULL, /* endDocument */ NULL, /* startElement*/ NULL, /* endElement */ NULL, /* reference */ charactersFoundSAX, /* characters */ NULL, /* ignorableWhitespace */ NULL, /* processingInstruction */ NULL, /* comment */ NULL, /* warning */ errorEncounteredSAX, /* error */ NULL, /* fatalError //: unused error() get all the errors */ NULL, /* getParameterEntity */ NULL, /* cdataBlock */ NULL, /* externalSubset */ XML_SAX2_MAGIC, // NULL, startElementSAX, /* startElementNs */ endElementSAX, /* endElementNs */ NULL, /* serror */ }; Thanks.

    Read the article

  • iPhone Table View Cell Image: Working on simulator, not showing on real device

    - by Graeme
    Hi, I have a UITable View that displays an image in the left hand side of the table cell, and it works fine in the simulator. Only problem is, once I ran it on my device no images appear. At first 3 did, but then I "cleaned headers" and now none appear. Have checked that images are added to resource folder for build (which they are) and that capitals etc. match (which they do). Any ideas? Thanks. Code to display images: cell.imageView.layer.masksToBounds = YES; cell.imageView.layer.cornerRadius = 5.0; UIImage *image = [UIImage imageNamed:[[dog types] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];; if ( image ) { cell.imageView.image = [image imageScaledToSize:CGSizeMake(50, 50)]; }

    Read the article

  • Why does IIS not support chunked transfer encoding?

    - by Graeme Perrow
    I am making an HTTP connection to an IIS web server and sending a POST request with the data encoded using Transfer-Encoding: chunked. When I do this, IIS simply closes the connection, with no error message or status code. According to the HTTP 1.1 spec, All HTTP/1.1 applications MUST be able to receive and decode the "chunked" transfer-coding so I don't understand why it's (a) not handling that encoding and (b) it's not sending back a status code. If I change the request to send the Content-Length rather than Transfer-Encoding, the query succeeds, but that's not always possible. When I try the same thing against Apache, I get a "411 Length required" status and a message saying "chunked Transfer-Encoding forbidden". Why do these servers not support this encoding?

    Read the article

  • Table image not showing, "Pop an autorelease pool" error

    - by Graeme
    hi, I have a UITableView which uses the following code to display an image in a Table View cell: cell.imageView.layer.masksToBounds = YES; cell.imageView.layer.cornerRadius = 5.0; UIImage *image = [UIImage imageNamed:[[color types] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]]; if ( image ) { cell.imageView.image = [image imageScaledToSize:CGSizeMake(50, 50)]; } It works fine on the iPhone simulator, but when I try it on a real iPhone the iPhone doesn't show. Instead in the console in debugging mode, I get this error: attempt to pop an unknown autorelease pool (0x851e00) Any help would be great, thanks.

    Read the article

  • 'NSInvalidArgumentException' UIButton IBAction Error

    - by Graeme
    Hi, I have a button in a view which refuses to work. I've got in working in a blank, default view application from X-Code, but in none of my applications will it work, instead it gives me the following error. Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[UIViewController showVicInfo:]: unrecognized selector sent to instance 0x3c084f0' The debugger isn't any help either. I've made sure that I hook up the button to the file's owner (not the other way around) as well. Below is the code for the action. And I know it's not the alert view, because the breakpoint doesn't even reach there. about.h @interface about : UIViewController { } -(IBAction)showInfo:(id)sender; about.m -(IBAction)showVicInfo:(id)sender { UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"No Internet Connection" message:@"You require an internet connection via WiFi or cellular network for iFirelert to work." delegate:self cancelButtonTitle:@"OK, thanks" otherButtonTitles:nil]; [myAlert show]; [myAlert release]; }

    Read the article

  • Problems removing a " from a string

    - by Graeme
    Hi, I have a string that ends with a " (quotation mark) that I want to get rid of. However, because XCode usually requires you to enter the text you wish to remove using stringByReplacingOccurrencesOfString in @"texttoremove" format, you can't use the quotation marks in the space as it thinks you are closing the text. Any ideas on how I can do it? Thanks.

    Read the article

  • Adding a dynamic image to UITable View Cell

    - by Graeme
    Hi, I have a table in which I want a dynamic image to load in at the left-hand side. The table needs to use an IF statement to select the appropriate image from the "Resources" folder, and needs to be based upon [dog types]. The [dog types] is extracted from an RSS feed, and so the image in the table cell needs to match the each cell's [dog types] tag. Update: See code below for what I'm looking to do (only below it's for earthquakes, for me its pictures of dogs). I suspect I need to use - (UIImage *)imageForTypes:(NSString *)types { to do such a thing. Thanks. Updated code: This is for Apple's Earthquake sample but does exactly what I need to do. It matches images to the severity (2.0, 3.0, 4.0, 5.0 etc.) of every earthquake to the magnitude. - (UIImage *)imageForMagnitude:(CGFloat)magnitude { if (magnitude >= 5.0) { return [UIImage imageNamed:@"5.0.png"]; } if (magnitude >= 4.0) { return [UIImage imageNamed:@"4.0.png"]; } if (magnitude >= 3.0) { return [UIImage imageNamed:@"3.0.png"]; } if (magnitude >= 2.0) { return [UIImage imageNamed:@"2.0.png"]; } return nil; } and under - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath magnitudeImage.image = [self imageForMagnitude:earthquake.magnitude];

    Read the article

  • Best way to change XIB files based on rotation?

    - by Graeme
    Hi, My app has so far just been a portrait-based application. However, I am adding landscape mode to a new version, but have found that my XIB files look shocking when rotated from portrait to landscape. Apparently I need to make a landscape version of each XIB and use some code to change with XIB launches based on what rotation occurs. Am I right? If so, where do I go from here? Are there any Apple sample apps utilising this code? FYI - My XIB files just have text in them. Thanks.

    Read the article

  • paypal redirect on successful checkout

    - by Graeme Leighfield
    I am trying to get my Paypal subscription to redirect to a custom page after a successful checkout. Before submitting to Paypal I overload the submit handler, run my own function (to store details) and return a unique id. I want to attach that id to my return URL. (as a GET or POST var so to speak) I have turned auto redirect "on" in my Paypal sandbox sellers preferences, but it only seems to re-direct to the URL that I HAVE to put in there. using the <input type="hidden" name="return" value="someurl" /> does no seem to work. I want it this way so that I can capture the user information when entered with a "non-paid" flag, then via the IPN I can update that record with a "PAID" flag, and I want to use the unique ID to tie it all together so to speak. Any advice or a different approach is welcomed. Many thanks!

    Read the article

  • Problems pulling data from NSMutableArray for MapKit?

    - by Graeme
    Hi, I have a class (DataImporter) which has the code to download an RSS feed. I also have a view and separate class (TableView) which displays the data in a UITableView and starts the parsing process, storing parsed information in an NSMutableArray (items). Now I wish to add a UIMapView which displays the items in the items NSMutableArray. I'm struggling to transfer the data into the new class (mapView) to show it in the map - and I preferably don't want to have to create a new class to download the data again for the map. Is there a way I can transfer the information from the NSMutableArray (items) to the mapView? Thanks. Code for viewDidLoad MapKit: Data *data = nil; NSString *ilocation = [data locations]; NSString *ilocation2 = @"New Zealand"; NSString *inewlString; inewlString = [ilocation stringByAppendingString:ilocation2]; NSLog(@"inewlString=%@",inewlString); if(forwardGeocoder == nil) { forwardGeocoder = [[BSForwardGeocoder alloc] initWithDelegate:self]; } // Forward geocode! [forwardGeocoder findLocation: inewlString]; Code for parsing data into NSMutable Array: - (void)beginParsing { NSLog(@"Parsing has begun"); //self.navigationItem.rightBarButtonItem.enabled = NO; // Allocate the array for song storage, or empty the results of previous parses if (incidents == nil) { NSLog(@"Grabbing array"); self.datas = [NSMutableArray array]; } else { [datas removeAllObjects]; [self.tableView reloadData]; } // Create the parser, set its delegate, and start it. self.parser = [[DataImporter alloc] init]; parser.delegate = self; [parser start]; }

    Read the article

  • Accessing items separated by -componentsSeparatedByString

    - by Graeme
    Hi, I have an array gathered by componentsSeparatedByString: that looks like the following when I use po in the GDB after the array has gone through componentsSeparatedByString: "\n\t\t <b>Suburb, </b> BAIRNSDALE", "\n\t\t <b>Address, </b> 15K NW BAIRNSDALE", "\n\t\t <b>Reference, </b> MELWOOD/SCHOOL ROAD", "\n\t\t <b>Last Changed, </b> 09/04/10 05, 29, 00 PM", "\n\t\t <b>Type, </b> HOME", "\n\t\t <b>Status, </b> BUILT", "\n\t\t <b>Property Size, </b> 2.00 HA.", "\n\t\t <b>Residents, </b> 2", "\n\t\t <b>First Added Date/Time, </b> 09/04/10 03, 15, 00 PM", "\n\t\t\t" Only problem is, I now can't figure out where to go from here. I need to be able to access each of these items (i.e. type, status, property size) separately rather than just calling the entire array (i.e. currentProperty.status). How do I do this? Also what's with all the n\t\t\t things - how do I get rid of them? Thanks.

    Read the article

< Previous Page | 1 2 3 4  | Next Page >