code

Objective-C는 C #과 어떻게 다릅니 까?

codestyles 2020. 9. 13. 10:34
반응형

Objective-C는 C #과 어떻게 다릅니 까? [닫은]


최근에 Mac을 구입했으며 주로 VMWare Fusion에서 C # 개발에 사용합니다. 주변의 모든 멋진 Mac 응용 프로그램과 함께 Xcode가 설치 클릭 한 번으로 숨어있는 것을 생각하고 Objective-C를 배우기 시작했습니다.

Objective-C의 기원은 C이고 C #의 기원은 Java / C ++이기 때문에 두 언어 간의 구문은 매우 다르게 보입니다. 그러나 다른 구문을 배울 수 있으므로 괜찮습니다.

내 주요 관심사는 언어로 작업하고 잘 구조화되고 읽기 쉽고 우아한 코드를 생성하는 데 도움이되는지 여부입니다. 저는 C #의 LINQ 및 var와 같은 기능을 정말 좋아하고 Objective-C에 동등하거나 더 나은 / 다른 기능이 있는지 궁금합니다.

Objective-C로 개발할 때 놓친 언어 기능은 무엇입니까? 어떤 기능을 얻을 수 있습니까?

편집 : 프레임 워크 비교는 유용하고 흥미롭지 만 언어 비교는이 질문이 실제로 묻는 것입니다 (부분적으로 원래 태그에 대한 내 잘못입니다 .net). 아마도 Cocoa와 .NET은 그 자체로 매우 풍부한 프레임 워크이며 둘 다 목적이 있습니다. 하나는 Mac OS X를 대상으로하고 다른 하나는 Windows를 대상으로합니다.

지금까지 잘 생각하고 합리적으로 균형 잡힌 견해에 감사드립니다!


모든 작업에 완벽한 언어는 없으며 Objective-C도 예외는 아니지만 매우 구체적인 장점이 있습니다. LINQand var(내가 직접 대체하는 것을 알지 못함) 사용 마찬가지로 이들 중 일부는 엄격하게 언어와 관련이 있고 다른 일부는 프레임 워크와 관련됩니다.

( 참고 : C #이 .NET과 밀접하게 결합 된 것처럼 Objective-C는 Cocoa와 밀접하게 결합되어 있습니다. 따라서 내 요점 중 일부는 Objective-C와 관련이없는 것처럼 보일 수 있지만 Cocoa가없는 Objective-C는 .NET이없는 C #과 유사합니다. WPF / LINQ, Mono에서 실행되는 등. 일반적으로 수행되는 방식이 아닙니다.)

차이점, 장단점을 완전히 설명하는 척하지는 않겠지 만, 여기에 떠오르는 몇 가지 사항이 있습니다.

  • Objective-C의 가장 좋은 부분 중 하나는 동적 특성입니다. 메서드를 호출하는 대신 런타임이 동적으로 라우팅하는 메시지를 보냅니다. 동적 타이핑과 (현명하게) 결합하면 많은 강력한 패턴을 구현하기가 더 간단하거나 사소하게 만들 수 있습니다.

  • C의 엄격한 상위 집합으로서 Objective-C는 사용자가 무엇을하고 있는지 알고 있다고 신뢰합니다. C # 및 Java와 같은 언어의 관리 및 / 또는 형식 안전 접근 방식과 달리 Objective-C를 사용하면 원하는 작업을 수행하고 그 결과를 경험할 수 있습니다. 분명히 이것은 때때로 위험 할 수 있지만 언어가 대부분의 작업을 적극적으로 방해하지 않는다는 사실은 매우 강력합니다. ( 편집 : C #에도 "안전하지 않은"기능과 기능이 있음을 명확히해야하지만 기본 동작은 명시 적으로 옵트 아웃해야하는 관리 코드입니다. 이에 비해 Java 는 형식이 안전한 코드 허용하며 원시 포인터를 노출하지 않습니다. C와 다른 사람들이하는 방식.)

  • 카테고리 (서브 클래 싱없이 클래스에 메서드 추가 / 수정 또는 소스에 대한 액세스 권한이 없음)는 멋진 양날의 검입니다. 상속 계층 구조를 대폭 단순화하고 코드를 제거 할 수 있지만 이상한 작업을 수행하면 결과가 당황 스러울 수 있습니다.

  • Cocoa는 여러 가지 방법으로 GUI 앱을 훨씬 더 간단하게 만들 수 있지만, 패러다임에 머리를 감아 야합니다. MVC 디자인은 Cocoa에 널리 퍼져 있으며 델리게이트, 알림 및 다중 스레드 GUI 앱과 같은 패턴은 Objective-C에 매우 적합합니다.

  • Cocoa 바인딩 및 키-값 관찰은 수많은 글루 코드를 제거 할 수 있으며 Cocoa 프레임 워크는이를 광범위하게 활용합니다. Objective-C의 동적 디스패치는 이와 함께 작동하므로 키-값을 준수하는 한 객체의 유형은 중요하지 않습니다.

  • 제네릭과 네임 스페이스를 놓칠 가능성이 높고 이점이 있지만 Objective-C 사고 방식과 패러다임에서는 필수품이 아니라 멋짐 일 것입니다. (제네릭은 모두 유형 안전성과 캐스팅 방지에 관한 것이지만, Objective-C의 동적 타이핑은 본질적으로 문제가되지 않습니다. 네임 스페이스는 잘 수행하면 좋겠지 만 비용이 이점을 능가하는 충돌을 피할 수있을만큼 간단합니다. 특히 레거시 코드의 경우.)

  • 동시성을 위해 Blocks (Snow Leopard의 새로운 언어 기능이며 수많은 Cocoa API에 구현 됨)는 매우 유용합니다. 몇 줄 (자주 10.6에서 libsystem의 일부인 Grand Central Dispatch와 결합 됨)은 콜백 함수, 컨텍스트 등의 중요한 상용구를 제거 할 수 있습니다. (블록은 C 및 C ++에서도 사용할 수 있으며 확실히 C #에 추가 될 수 있습니다. NSOperationQueue는 또한 GCD가 하나 이상의 다른 스레드에서 자동으로 실행되는 사용자 지정 NSOperation 하위 클래스 또는 익명 블록을 발송하여 자신의 코드에 동시성을 추가하는 매우 편리한 방법입니다.


저는 1990 년에 처음 시작된 20 년 넘게 C, C ++ 및 C #으로 프로그래밍했습니다. 방금 iPhone 개발과 Xcode 및 Objective-C를 살펴보기로 결정했습니다. 오, 세상에 .. 마이크로 소프트에 대한 모든 불만을 되찾았고, 이제 코드가 얼마나 나쁜지 알게되었습니다. Objective-C는 C #이하는 일에 비해 너무 복잡합니다. 나는 C #에 푹 빠졌고 이제 마이크로 소프트가 해준 모든 노력에 감사드립니다. 메소드 호출로 Objective-C를 읽는 것만으로는 읽기가 어렵습니다. C #은이 점에서 우아합니다. 그것은 제 생각에 불과합니다. 저는 Apple 개발 언어가 Apple 제품만큼 좋기를 바랐지만, 저는 Microsoft로부터 배울 것이 많습니다. C # .NET 응용 프로그램에 대한 의문의 여지가 없습니다. XCode Objective-C보다 몇 배 더 빠르게 응용 프로그램을 설치하고 실행할 수 있습니다. 애플은 확실히 마이크로 소프트에서 잎을 제거해야한다. ' 여기에 책이 있으면 우리는 완벽한 환경을 갖게 될 것입니다. :-)


여기에 기술적 인 리뷰는 없지만 Objective-C가 훨씬 읽기 어렵습니다. Cinder6이 제공 한 예가 다음과 같습니다.

씨#

List<string> strings = new List<string>();
strings.Add("xyzzy");                  // takes only strings
strings.Add(15);                       // compiler error
string x = strings[0];                 // guaranteed to be a string
strings.RemoveAt(0);                   // or non-existant (yielding an exception)

목표 -C

NSMutableArray *strings = [NSMutableArray array];
[strings addObject:@"xyzzy"];
[strings addObject:@15];
NSString *x = strings[0];
[strings removeObjectAtIndex:0];

끔찍해 보입니다. 두 권의 책을 읽으려고했는데, 그들은 일찍 나를 잃었고, 보통은 프로그래밍 책 / 언어로는 이해하지 못합니다.

좋은 개발 환경을 제공하기 위해 Apple에 의존해야한다면 Mac OS 용 Mono를 사용하게되어 기쁩니다.


수동 메모리 관리는 Objective-C의 초보자가 가장 문제가 많은 것 같습니다. 대부분은 그것이 실제보다 더 복잡하다고 생각하기 때문입니다.

Objective-C와 Cocoa는 확장을 통해 시행에 대한 관습에 의존합니다. 아주 작은 규칙 세트를 알고 따르면 동적 런타임으로 많은 것을 무료로 얻을 수 있습니다.

100 % 진정한 규칙은 아니지만 매일 사용하기에 충분합니다.

  • Every call to alloc should be matched with a release at the end of the current scope.
  • If the return value for your method has been obtained by alloc then it should be returned by return [value autorelease]; instead of being matched by a release.
  • Use properties, and there is no rule three.

The longer explanation follows.

Memory management is based on ownership; only the owner of an object instance should ever release the object, everybody else should always do nothing. This mean that in 95% of all code you treat Objective-C as if it was garbage collected.

So what about the other 5%? You have three methods to look out for, any object instance received from these method are owned by the current method scope:

  • alloc
  • Any method beginning with the word new, such as new or newService.
  • Any method containing the word copy, such as copy and mutableCopy.

The method have three possible options as of what to do with it's owned object instances before it exits:

  • Release it using release if it is no longer needed.
  • Give ownership to the a field (instance variable), or a global variable by simply assigning it.
  • Relinquish ownership but give someone else a chance to take ownership before the instance goes away by calling autorelease.

So when should you pro-actively take ownership by calling retain? Two cases:

  • When assigning fields in your initializers.
  • When manually implementing setter method.

Sure, if everything you saw in your life is Objective C, then its syntax looks like the only possible. We could call you a "programming virgin".

But since lots of code is written in C, C++, Java, JavaScript, Pascal and other languages, you'll see that ObjectiveC is different from all of them, but not in a good way. Did they have a reason for this? Let's see other popular languages:

C++ added a lot extras to C, but it changed the original syntax only as much as needed.

C# added a lot extras compared to C++ but it changed only things that were ugly in C++ (like removing the "::" from the interface).

Java changed a lot of things, but it kept the familiar syntax except in parts where the change was needed.

JavaScript is a completely dynamic language that can do many things ObjectiveC can't. Still, its creators didn't invent a new way of calling methods and passing parameters just to be different from the rest of the world.

Visual Basic can pass parameters out of order, just like ObjectiveC. You can name the parameters, but you can also pass them the regular way. Whatever you use, it's normal comma-delimited way that everyone understands. Comma is the usual delimiter, not just in programming languages, but in books, newspapers, and written language in general.

Object Pascal has a different syntax than C, but its syntax is actually EASIER to read for the programmer (maybe not to the computer, but who cares what computer thinks). So maybe they digressed, but at least their result is better.

Python has a different syntax, which is even easier to read (for humans) than Pascal. So when they changed it, making it different, at least they made it better for us programmers.

And then we have ObjectiveC. Adding some improvements to C, but inventing its own interface syntax, method calling, parameter passing and what not. I wonder why didn't they swap + and - so that plus subtracts two numbers. It would have been even cooler.

Steve Jobs screwed up by supporting ObjectiveC. Of course he can't support C#, which is better, but belongs to his worst competitor. So this is a political decision, not a practical one. Technology always suffers when tech decisions are made for political reasons. He should lead the company, which he does good, and leave programming matters to real experts.

I'm sure there would be even more apps for iPhone if he decided to write iOS and support libraries in any other language than ObjectiveC. To everyone except die-hard fans, virgin programmers and Steve Jobs, ObjectiveC looks ridiculous, ugly and repulsive.


One thing I love about objective-c is that the object system is based on messages, it lets you do really nice things you couldn't do in C# (at least not until they support the dynamic keyword!).

Another great thing about writing cocoa apps is Interface Builder, it's a lot nicer than the forms designer in Visual Studio.

The things about obj-c that annoy me (as a C# developer) are the fact that you have to manage your own memory (there's garbage collection, but that doesn't work on the iPhone) and that it can be very verbose because of the selector syntax and all the [ ].


As a programmer just getting started with Objective-C for iPhone, coming from C# 4.0, I'm missing lambda expressions, and in particular, Linq-to-XML. The lambda expressions are C#-specific, while the Linq-to-XML is really more of a .NET vs. Cocoa contrast. In a sample app I was writing, I had some XML in a string. I wanted to parse the elements of that XML into a collection of objects.

To accomplish this in Objective-C/Cocoa, I had to use the NSXmlParser class. This class relies on another object which implements the NSXMLParserDelegate protocol with methods that are called (read: messages sent) when an element open tag is read, when some data is read (usually inside the element), and when some element end tag is read. You have to keep track of the parsing status and state. And I honestly have no idea what happens if the XML is invalid. It's great for getting down to the details and optimize performance, but oh man, that's a whole lot of code.

By contrast, here's the code in C#:

using System.Linq.Xml;
XDocument doc = XDocument.Load(xmlString);
IEnumerable<MyCustomObject> objects = doc.Descendants().Select(
         d => new MyCustomObject{ Name = d.Value});

And that's it, you've got a collection of custom objects drawn from XML. If you wanted to filter those elements by value, or only to those that contain a specific attribute, or if you just wanted the first 5, or to skip the first 1 and get the next 3, or just find out if any elements were returned... BAM, all right there in the same line of code.

There are many open-source classes that make this processing a lot easier in Objective-C, so that does much of the heavy lifting. It's just not this built in.

*NOTE: I didn't actually compile the code above, it's just meant as an example to illustrate the relative lack of verbosity required by C#.


Probably most important difference is memory management. With C# you get garbage collection, by virtue of it being a CLR based language. With Objective-C you need to manage memory yourself.

If you're coming from a C# background (or any modern language for that matter), moving to a language without automatic memory management will be really painful, as you will spend a lot of your coding time on properly managing memory (and debugging as well).


Here's a pretty good article comparing the two languages: http://www.coderetard.com/2008/03/16/c-vs-objective-c/


Other than the paradigm difference between the 2 languages, there's not a lot of difference. As much as I hate to say it, you can do the same kind of things (probably not as easily) with .NET and C# as you can with Objective-C and Cocoa. As of Leopard, Objective-C 2.0 has garbage collection, so you don't have to manage memory yourself unless you want to (code compatibility with older Macs and iPhone apps are 2 reasons to want to).

As far as structured, readable code is concerned, much of the burden there lies with the programmer, as with any other language. However, I find that the message passing paradigm lends itself well to readable code provided you name your functions/methods appropriately (again, just like any other language).

I'll be the first to admit that I'm not very familiar with C# or .NET. But the reasons Quinn listed above are quite a few reasons that I don't care to become so.


The method calls used in obj-c make for easily read code, in my opinion much more elegant than c# and obj-c is built on top of c so all c code should work fine in obj-c. The big seller for me though is that obj-c is an open standard so you can find compilers for any system.

참고URL : https://stackoverflow.com/questions/1369078/how-does-objective-c-compare-to-c

반응형