Calling a method from another class in Objective-C [closed] - objective-c

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I'm trying to get to grips with Objective-C, having programmed in Java and C in the past.
I have a class, Unzip, which contains the following method:
- (void)unzipFile:(NSString*)fileName
I'm trying to call this method from the AppDelegate class, to respond to a button click, using the following code, which creates an instance of Unzip and calls the unzipFile method with a string value, but nothing happens.
- (IBAction)unzipIt:(id)sender {
NSLog(#"Unzip clicked");
NSString *zipString = [_testField stringValue];
NSLog(#"Calling unzip with the string %#", zipString);
Unzip *unzip;
[unzip unzipFile:(zipString)];
}
The actual button click works, because the two initial NSLogs appear, but nothing further happens. The method is fine as I've tested it elsewhere so at least something should happen. Could anybody please tell me where I'm going wrong?
Thanks for your time.

You didn't allocate Unzip:
Unzip *unzip = [[Unzip alloc] init];
[unzip unzipFile:zipString];
The reason why it is not working, but not blowing up, is in Objective C, it is safe to send a message to nil.
Some more concepts about Objective C, especially in the section Working with Nil.

You have to initialize your unzip variable
Unzip *unzip = [[Unzip alloc] init];
There is also a shortcut:
Unzip *unzip = [Unzip new];
which is equivalent shorthand.

Related

Compile error cause by NSAray [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 8 years ago.
Improve this question
As you'll see from the code in the xcode project file there's a compile error at build time.
I'm trying to apply names for the indivudal image using the following code:
labelArray =[[NSArray alloc] initWithObjects:#"one", #"two", #"three", #"four", nil];
cell.label.text = [_labelArray objectAtIndex:indexPath.row];
This is using apples sample code for collection view but the principals are the same for my project.
Here's a drop box link for the compile error issue using an NSArray with a uilabel..
The error is:
Interface storyboard compile error.
Any thoughts on this would be great.
Cheers
I don't kwow about your storyboard issue (it is impossible to say anything without seeing the storyboard, or, at least, how the outlet is bound), but there is another issue.
It seems like labelArray is an array of UILabel. But in the first line of your code, you are creating an array of NSString.

How do I use the CHCSV parser?

I am new to the programming world and learning iPhone app development. For one of my apps, I am downloading CSV data from Yahoo finance. I want to have it in a dictionary. After some searches, I found the CHCSV parser. My question is how to use it?
I copied the files into my project and tried its different methods. I know my approach is kind of silly. As a novice in these things, I would really appreciate it if someone can help me out. In the following code I am initializing a CHCSV object by passing in the CSV file. I guess the parse method is the right one to use. After that, I have no clue how to get a dictionary out of it.
#import "ifinance5ViewController.h"
#import "CHCSV.h"
#implementation ifinance5ViewController
#synthesize button1;
-(IBAction)buttonpressed:(UIButton*)sender{
NSString *locfile = #"/Users/---/Desktop/array.csv";
NSError *anError = nil;
[CHCSV *csvfile]=[[CHCSV alloc]initWithContentsOfCSVFile:(NSString *)locfile usedEncoding:(NSStringEncoding *)NSASCIIStringEncoding error:(NSError **)anError];
[csvfile parse];
}

Objective-C - Category to return a specific font?

I am trying to write a category and override fontWithName:size in UIFont. I am doing this for unit testing to avoid crashes caused by font names that are available on ipad and not on OSX. So I need to return a simple font that exists on both platform doesn't matter what the nib or code requests.
I tried the following but I run into an infinite loop, any idea on how I can achieve this?
+ (UIFont *)fontWithName:(NSString *)fontName size:(CGFloat)fontSize
{
return [UIFont fontWithName:#"Arial" size:fontSize];
}
Edit:
I also tried returning a CTFont but my test target does not recognize CTFont? Any idea what header I should import to use CTFont?
+ (UIFont *)fontWithName:(NSString *)fontName size:(CGFloat)fontSize
{
return [[[NSFont alloc] init] autorelease];
}
The above solution is an answer to my question.
But for fixing the unit testing problem I ended up running them as application tests instead of logic tests, that way they run in the iOS environment and they don't crash. The change was to set my Bundle Loader to point to my application target, and set the Test Host to post to my Bundle Loader.
By creating a category that has a method with the same you have replaced the original method. Therefore the following call is a recursive one: [UIFont fontWithName:#"Arial" size:fontSize];
I would create a new method with a different name (especially as the fontName parameter of your new method is unused), and switch all existing calls to use that.
See the accepted answer to this question for further discussion: Using Super in an Objective C Category?

Weird EXC_BAD_ACCESS in a trivial PDFKit program

I have written this trivial action method associated to a textfield.
Every time I enter text into a textfield a search in a PDF is performed and PDFView automatically scroll to selection:
- (IBAction) search:(id)id
{
NSString *query = [self.searchView stringValue]; // get from textfield
selection = [document findString: query fromSelection:NULL withOptions:NSCaseInsensitiveSearch];
if (selection != nil)
{
[self.pdfView setCurrentSelection:selection];
[self.pdfView scrollSelectionToVisible:self.searchView];
}
}
Problem is that after 3 or 4 searches I get EXC_BAD_ACCESS on row (i).
If I debug I see that query contains an NSCFString and not an NSString.
I think it is a memory management problem..but where?
I replicated the same issue inside a trivial testcase:
#interface PDFRef_protoTests : SenTestCase {
#private
PDFDocument *document;
}
........
- (void)setUp
{
[super setUp];
document = [[PDFDocument alloc] initWithURL: #"a local url ..."];
}
- (void)test_exc_bad_access_in_pdfdocument
{
for (int i =0 ;i<100; i++)
{
NSString *temp;
if (i % 2 == 0) temp = #"home";
else if (i % 3 ==0) temp = #"cocoa";
else temp=#"apple";
PDFSelection *selection = [document findString: temp
fromSelection:nil
withOptions:NSCaseInsensitiveSearch];
NSLog(#"Find=%#, iteration=%d", selection, i);
}
}
Update:
1) It seems that it happens also if I use asynchronous search (method beginFindString: withOptions) every time I perform second search.
2) I found a similar problem to mine in MacRuby Issue Tracking: http://www.macruby.org/trac/ticket/1029
3) It seems that if I disable temporarily garbage collection it works but memory goes up.
I wrote something like:
[[NSGarbageCollector defaultCollector] disable];
[[NSGarbageCollector defaultCollector] enable];
surrounding search code
Another Update
Very weird thing is that sometimes all works. Than I clean and Rebuild and problem arises again. From a certain point of view is is not 100% reproducible. I suspect a bug in PDFKit or some compiler setting I have to do
Update Again
Dears it seems very crazy. I'd concentrate on testcase which is very trivial and which replicates easily the problem. What's wrong with it? This testcase works only if I disable (by code or by project setting) GC
Another Update
Boys it seems a bug but I downloaded an example called PDFLinker from Apple website (http://developer.apple.com/library/mac/#samplecode/PDFKitLinker2/Introduction/Intro.html#//apple_ref/doc/uid/DTS10003594). This example implements a PDFViewer. Code of my app and this example are quite similars. For the same search action on same PDF, my memory rises at 300/400 MB while PDFLinker rises at 190MB. Clearly there is something wrong in my code. But I am comparing it bit by bit and I don't think I am inserting memory leaks (and Instrument doesn't give me any evidence). Maybe is there some project-wide setting ?
Update Yet
Changing from 64 bit to 32 bit memory consumption lowered. Surely there is a problem with 64bit and PDFKit. BTW still EXC_BAD_ACCESS on second search
SOLUTION
Crucial point is that PDFKit with Garbage collection is bugged.
If I disable GC all works correctly.
I had another issue that had complicated my analysis: I disabled GC on Project Setting but GC remained enabled on Target Settings. So Apple's example PDFLinked2 worked while mine not.
I agree you have found a bug in PDFKit.
I got various forms of errors (segmentation fault, selector not understood, etc) running your test case. Wrapping the code in #try/#catch doesn't prevent all errors associated with this method.
I also got errors printing the log message.
To work around the bug(s), I suggest you disable GC during your invocation of -findString:fromSelection:, as you've already discovered.
Also, be sure to make copies of the values of interest from selection before re-enabling GC. Don't just copy selection either.
If you conduct searches from multiple places in your code I also suggest you extract a separate method to perform the search. Then you can invoke that one to conduct the searches for you without duplicating the GC disable/enable nesting.
This sort of thing is usually evidence that you're hanging onto a pointer to an object that has been destroyed. Turn on zombie objects (with NSZombieEnabled) to see exactly where and when you're accessing a bad object.
Judging from your screen shot it doesn't seem like you have NSZombie turned on. Probably the reason why it doesn't help you. Here's how you turn it on:
How to enable NSZombie in Xcode?
The screenshot you provided was otherwise very useful, but you really need NSZombie to figure out this kind of errors. Well, unless it's obvious, which it isn't from the code you posted.
EDIT: I read the comment that you're using garbage collection. I'm an iOS developer, so I have very limited experience with garbage collection in Objective-C, but as far as I understand NSZombie doesn't work in a garbage collected environment.
I'm not sure it should be possible to get EXC_BAD_ACCESS in a garbage collected environment, unless you create your own pointer and try to call methods on it without having created an object and I don't see why you would do that.
I've heard that some frameworks doesn't work well with garbage collection, but I wouldn't think PDFKit was among them. Anyway, the solution might be to not use garbage collection. Perhaps you should file a bug report with Apple.
keep PDFSelection *selection as a member variable and pass it in fromSelection: instead of nil.
It is possible that PDFDocument keeps the returned PDFSelection instance to improve the performance.
Did you try retaining the searchview stringvalue object before using it?
As you say it happens when you type fast and it happens for async calls, it is possible that the object stringValue is pointing to is being released between the time your query object is pointing to it, and the time you use it int the search.
You could try something like this to see if the problem persists:
- (IBAction) search:(id)id
{
NSString *query = [[self.searchView stringValue] retain]; // get from textfield
selection = [document findString: query fromSelection:NULL withOptions:NSCaseInsensitiveSearch];
if (selection != nil)
{
[self.pdfView setCurrentSelection:selection];
[self.pdfView scrollSelectionToVisible:self.searchView];
}
[query release];
}
Of course there is also the possibility that document is relased. How do you declare it? is it a property with retain? Can it be released by the time you are searching?
EDIT:
I see that you posted the code with the second parameter as NULL, but in your screenshot, this value is nil.
The documentation says you should use NULL when you want to start the search from the beginning.
http://developer.apple.com/library/mac/#documentation/GraphicsImaging/Reference/QuartzFramework/Classes/PDFDocument_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40003873-RH2-DontLinkElementID_1
And as the compiler interprets nil and NULL differently, this could be leading to some weird behavior internally.

No stringWithContentsofURL method found

I'm following this tutorial, attempting to learn a bit about iPhone development, and there come a point where the author uses the stringWithContentsofURL method but xcode is telling me that there is no stringWithContentsofURL method found. I've done some searching and I've not been able to come up with a solution. This is a screen shot of the xcode window displaying the error:
alt text http://mywebprogrammer.com/so/obj-c%20problem%200.png
stringWithContentsofURL: is a class method, not an instance method, so you have to use it as
[NSString stringWithContentsOfURL:myURL]
or if you want to allocate it yourself, you would do:
[[NSString alloc] initWithContentsOfURL:myURL]
but then you would have to release it later
Its [NSString stringWithContentsOfURL]. Note: its the capital 'O' (in Of) not small 'o' as given by you. Also Its a static method so cannot be used against an object.